首页 > 解决方案 > 在 Firestore [通配符] 中为点注释的动态路径创建索引?

问题描述

我的收藏创​​建如下:

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

现在我写了一个查询如下

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

此查询工作正常,但是当我将 orderBy 添加到上述查询时,我被要求index为查询创建一个。

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

由于categoryName可以创建并且可以随时更改,我应该为每个 categoryName 添加索引,这将是数百个。

有什么方法可以创建通配符索引category.categoryName吗?

我尝试使用category.*,但这是不可接受的。希望能在这里找到一些帮助。

标签: firebaseindexinggoogle-cloud-firestorecomposite-index

解决方案


自从提出这个问题以来,Firestore 已经实现了各种运算符来帮助查询数组成员资格。在撰写本文时可用的运算符有:array-containsarray-contains-anyinnot-in

您可以拥有一个包含产品所属类别的名称(或者,如果您想节省空间,则为id)的数组,而不是将其存储category为eachobject的属性。BooleancategoryNamecategoriesStringInt

然后查询可以像这样工作,只需要一个索引:

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

推荐阅读