Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algolia filter by nested attribute JavaScript

So I am using Algolia.com to index users for quick searching.

An example object in index:

{
    id: 1,
    username: "john.doe",
    name: "John Doe",
    attributes: {
        gender: "male",
        hair_color: "blonde",
        eye_color: "blue",
        height: 165
    }
}

I'd like to filter results by a specific attribute (object key) in the attributes object.

I thought maybe using facetFilters would do the job, but I am unable to get it working.

I have tried many variances of this code:

user_index.search('', {
    facets: '*',
    facetFilters: ['attributes.hair_color:blonde', 'attributes.eye_color:blue']
}, function(error, data) {
    console.log(error, data);
});

-- / --

user_index.search('', {
    facets: '*',
    facetFilters: ['hair_color:blonde']
}, function(error, data) {
    console.log(error, data);
});

Please find the documentation here: https://www.algolia.com/doc/javascript

like image 866
Levi Cole Avatar asked Oct 24 '25 15:10

Levi Cole


2 Answers

Just in order to be able to mark this question as answered :

You should add attributes.hair_color to your attributesForFaceting (Display tab in your index dashboard) You should be able to easily just do

user_index.search('', {
  facetFilters: 'attributes.hair_color:blonde'
}, function () {
  console.log(arguments);
});

to search.

like image 172
Jerska Avatar answered Oct 26 '25 04:10

Jerska


Sounds like using facet filters is the best way to achieve what you're looking for. The easiest way is to handle those filters is probably to use the Javascript Helper https://github.com/algolia/algoliasearch-helper-js#filtering-results.

You would then only need to call

helper.addFacetRefinement('hair_color', 'blonde').search();
like image 31
Alex C Avatar answered Oct 26 '25 03:10

Alex C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!