Multiple indices with one search field in instantsearch.js (frontend only)

Does anyone know how to use one search field to address multiple indices? In my case it should both search for common search queries and show them + the search results for the current search query in the InLearnity database. The script works perfectly in the previous version for one index. But when I changed it to work with multiple indices like the following code, it doesn’t work anymore.

<script src="https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
<script>
                var searchInLearnity = instantsearch({
                    appId: 'IONWXXXXX',
                       apiKey: '39e1b17cb2d0406xxxxxxxxxxxxx',
                    indexName: 'InLearnity',
                    urlSync: true
                });
                
                var searchQueries = instantsearch({
                    appId: 'IONWXXXXX',
                       apiKey: '39e1b17cb2d0406xxxxxxxxxxxxx',
                    indexName: 'search queries',
                    urlSync: true
                });

                var searchBox = instantsearch.widgets.searchBox({
                        container: '#search-input'});
                        
                searchInLearnity.addWidget(searchBox);
                searchQueries.addWidget(searchBox);

                
                searchInLearnity.addWidget(
                    instantsearch.widgets.infiniteHits({
                    container: '#hits',
                    hitsPerPage: 8,
                    templates: {
                    	empty: '',
                    	item: document.getElementById('hit-template').innerHTML
                        },
               		escapeHits: true,
                    })
                );

                searchInLearnity.addWidget(
  					instantsearch.widgets.stats({
    					ontainer: '#stats-container'
  						})
                );

                searchQueries.addWidget(
                    instantsearch.widgets.hits({
                    container: '#queries',
                    hitsPerPage: 4,
                    templates: {
                    	empty: '',
                    	item: document.getElementById('hit-template').innerHTML
                        },
               		escapeHits: true,
                    })
                );
                
                searchInLearnity.start();
                searchQueries.start();
                
</script>

Hi @MarcoEDU, you’ll find an example on how to do multi index search here: https://jsfiddle.net/j9nwpz34/27/

As you can see, there’s no need to add the searchbox widget to multiple instances, but rather connecting one instance to another through the searchFunction.

This one example is using InstantSearch.js V2, if you are early on in your development I suggest you switch to this version.

Let me know how it goes.

1 Like