3

I have my collection created as below:

-products
  -productID
    -category [object]
      catitem1 - boolean
      catitem2 - boolean

now I have written a query as below

this.afs.collection<Product>('products', ref =>
    ref
      .where(`category.${categoryName}`, '==', true)
      .limit(limit)
);

This query works fine but when I add orderBy to the above query, I am asked to create an index for the query.

this.afs.collection<Product>('products', ref =>
    ref
      .where(`category.${categoryName}`, '==', true)
      .orderBy('createdDate','desc')
      .limit(limit)
);

Since the categoryName can be created and can be changed at anytime, I am supposed to add indexing for each and every categoryName which would be in hundreds.

Is there any way where I can create a wildcard index for category.categoryName?

I tried using category.* but that's not acceptable. Hope to find some help here.

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • did you find solution to this? I'm currently in the same situation – ahmedjaad Jun 24 '20 at 23:26
  • @ahmedjaad nope I did not.. I had to change my functionality.. – Guruprasad J Rao Jun 25 '20 at 09:24
  • 1
    Thanks for the response, our case is a bit different from yours though, in our case the variable is the language we support in our app, and we only support a limited number of languages so i guess i will stick with creating index for each language, Hopefully will see such feature in the firestore – ahmedjaad Jun 25 '20 at 14:57

1 Answers1

3

Since this question was asked, Firestore has implemented various operators to help with querying for array membership. The available operators at time of writing are: array-contains, array-contains-any, in, and not-in.

Instead of storing category as an object with a Boolean property for each categoryName, you could have a categories array that only contains the String names (or, if you want to save space, Int ids) of categories that the product is a member of.

The query could then work like this, which would require only a single index:

this.afs.collection<Product>('products', ref =>
    ref
      .where('categories', 'array-contains', categoryName)
      .orderBy('createdDate','desc')
      .limit(limit)
);
bdrelling
  • 830
  • 1
  • 10
  • 27