Home > Net >  How to search inside an array property of an index
How to search inside an array property of an index

Time:01-16

I have to retrieve a list of apps that have certain string inside of an array property:

const users = algoliaClient.initIndex('apps')
return users.search('myId123', { hitsPerPage: 50 });

The apps objects are just like this:

{categories: ['an', 'interesting', 'category']}

How can I search the index for items with a categories property that contains any item in an array of strings?

CodePudding user response:

You can use the filter property in the search options to filter the results based on the categories property and the array of strings.

Here's an example:

const categoriesToSearch = ['an', 'interesting'];

return users.search({
    query: 'myId123', 
    hitsPerPage: 50, 
    filter: `categories:(${categoriesToSearch.join(' OR ')})`
});

In this example, the filter property is set to categories:(an OR interesting), which will search for apps that have either "an" or "interesting" in their categories property. You can also use the and operator instead of or if you want to search for apps that have all of the strings in the array in their categories property.

const categoriesToSearch = ['an', 'interesting'];

return users.search({
    query: 'myId123', 
    hitsPerPage: 10, 
    filter: `categories:(${categoriesToSearch.join(' AND ')})`
});

CodePudding user response:

const search = ["cat1", "cat2", "cat3"];
const apps = [
{
name: "app1",
categories: ["cat1", "cat5"],
},
{
name: "app2",
categories: ["cat2", "cat4"],
},
  ];

is that what you mean ? if so :

var myIndexes = [];

apps.forEach((app, index) => {
search.every((search) => {
  if (app.categories.includes(search)) {
    myIndexes.push(index);
    return false; // return false here is for stoping the EVERY loop
  } else {
    return true; // keep running the EVERY loop
  }
});
});
  • Related