Combine results from different indices and get the total number of results from all indices

Hi,

I have combined results from different indices and displaying in one widget area.

var searchBrands = algoliaBundle.instantsearch({appId:…});
searchBrands.addWidget({…});

var searchCategories = algoliaBundle.instantsearch({appId:…});
searchCategories.addWidget({…});

Now I want to hide the Related Pages section, when there are no results from both the indices. I can check the number of results from one indice inside the render function of each widget. But how can i know the total results of 2 indices and hide the entire Related pages section if the total is 0.

Please help me out if anybody have workaround ?

Thanks
Rajendra K.

Hi @rajendrak,

You can use the helpers of both instances for achieve such behaviour. If the helper is something new to you, this is the internal library used for managing the state of the search. You can find more informations about that in our documentation. You will need to listen for the result event on both helpers and then track the number total of results. When the number is equal to zero you can hide the content otherwise you show it. You ended up with something like this:

let nbHitsBrands = 0;
let nbHitsCategories = 0;

searchBrands.helper.on('result', function(results) {
  nbHitsBrands = results.nbHits;

  if (nbHitsBrands + nbHitsCategories === 0) {
    // Do whatever you want
  }
});

searchCategories.helper.on('result', function(results) {
  nbHitsCategories = results.nbHits;

  if (nbHitsBrands + nbHitsCategories === 0) {
    // Do whatever you want
  }
});

Hope that helps, let me know if you have questions :wink:

Hi Samuel,

I integrated Magento 2 Algolia extension. Does it have helper js included ?

Hi @rajendrak,

Yes but you don’t need to reference it globally. When you create your InstantSearch instance you have access to it directly. With your previous example, you will have something like:

var searchBrands = algoliaBundle.instantsearch({appId:…});
searchBrands.addWidget({…});

var searchCategories = algoliaBundle.instantsearch({appId:…});
searchCategories.addWidget({…});

searchBrands.start();
searchCategories.start();

// Now you have access to the helper through `searchBrands.helper`
searchBrands.helper.on('result', function(results) { ... });

Thanks Samuel,

It works for me.

But with small modification in the script.

I have changed the following line
searchCategories.helper.on(‘results’, function(results) {…

to
searchCategories.helper.on(‘result’, function(results) {…

Thanks for your help.

Hi @rajendrak,

Sorry for the typo… Glad to see that it works for you :slight_smile:

No Issues.

I posted another query.

Could you please look into it if you can help out.