Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating indexing for dot annotated dynamic path in firestore [Wildcard]?

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.

like image 507
Guruprasad J Rao Avatar asked Dec 18 '25 14:12

Guruprasad J Rao


1 Answers

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)
);
like image 102
bdrelling Avatar answered Dec 20 '25 22:12

bdrelling



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!