Mark Reiner
Mark Reiner

Reputation: 82

Efficiently retrieving all unique records for a facet value along with record counts in Algolia

I'm using Algolia to power search in my app. I have an index called prod_COACHES in which I have some records with an object key called speciality1.

The data structure for speciality1 looks like this:

enter image description here

I have enabled speciality1.itemName as an Algolia 'facet' so that I can filter on it. All good so far and working nicely. Now, in my Algolia dashboard I can see a nice bit of UI that shows me every unique facet (in this case my specialisations) along with the number of records for each facet:

enter image description here

As it happens, I want to show exactly this information on my own UI in my app but I'm not sure how to get this data from Algolia in the most efficient way. I'm using the client side AlgoliaSearch Javascript SDK. How do I run a search to retrieve every unique speciality1.itemName and the number of records for each unique speciality1.itemName so I can build my own UI just like the above?

I have gone through the docs and followed the examples but my question is really about finding the most efficient way to do this from someone who really knows Algolia well, rather than hack my own solution together. Thanks!

Upvotes: 0

Views: 333

Answers (1)

Samuel Vaillant
Samuel Vaillant

Reputation: 3857

It looks like you've enabled attributesForFaceting on the attribute speciality1.itemName. You can retrieve the facet values for the given attribue with the search parameter facets. The Algolia response will now contain a map with value:count. Here is an example with the JavaScript client:

import algoliasearch from 'algoliasearch';

const client = algoliasearch('XXX', 'XXX');
const index = client.initIndex('XXX');

index.search('', {
  facets: ['speciality1.itemName']
}).then(result => {
  console.log(result.facets)
});

If you want to easily build a search UI, you should take a look at the InstantSearch libraries. It's built on top of Algolia to ease the state/ui management for such UI. Many flavours are available e.g. Vanilla, React.

Upvotes: 0

Related Questions