filterfacetalgoliafaceted-search

Algolia filters on array property not working as expected


I have an index on algolia having users like this

UserA:

{
 createdAt: 1675364400000,
 email: "abc@gmail.com",
 products: [
   {
    productId: 'product1',
    dateAdded: 1675364400000,
    dateUpdated: 1675364400000,
    status: 'active'
   },
   {
    productId: 'product2',
    dateAdded: 1675364400000,
    dateUpdated: 1675364400000,
    status: 'pending'
   },
 ]
}

UserB:

{
 createdAt: 1675364400000,
 email: "abc1@gmail.com",
 products: [
   {
    productId: 'product4',
    dateAdded: 1675364400000,
    dateUpdated: 1675364400000,
    status: 'active'
   },
   {
    productId: 'product5',
    dateAdded: 1675364400000,
    dateUpdated: 1675364400000,
    status: 'pending'
   },
 ]
}

Need to apply filter on algolia to get all the users who has product2 with pending status. I'm getting both UserA (because it has product2 pending) and UserB (because it has product with pending status).

I added products.status and products.productId in attributesForFaceting and used the following in filters products.productId:product2 AND products.status:pending. Its getting all the users having product2 and any products with status pending


Solution

  • Changing the structure of the index on algolia helped me to resolve this issue. There are multiple ways to structure the index like mentioned in this but with this approach, can have redundant data and more requests to algolia if we need to update the other fields like createdAt in my case. Here is the structure I used to avoid all these overheads.

    {
     createdAt: 1675364400000,
     email: "abc@gmail.com",
     "product1": {
        productId: 'product1',
        dateAdded: 1675364400000,
        dateUpdated: 1675364400000,
        status: 'active'
      },
     "product2": {
        productId: 'product2',
        dateAdded: 1675364400000,
        dateUpdated: 1675364400000,
        status: 'pending'
      }
    }
    

    And in attributesForFaceting added product1.status, product2.status, and the same for all our products. In this way, if we need to update the createdAt on algolia, we must change just one object with no redundant data.

    We have a limited number of products that will not change very often. This might have some issues with attributesForFaceting if we have many products and change very often.

    I would love to hear suggestions for improvement.