Algolia filter by nested attribute JavaScript

对着背影说爱祢 提交于 2019-12-22 11:28:15

问题


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


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/33910947/algolia-filter-by-nested-attribute-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!