Firestore,如何合并包含多个范围比较的查询的索引?

时间:2019-05-14 13:32:02

标签: firebase react-native indexing filter google-cloud-firestore

所以我收藏的每个文档都包含五个不同的字段,即:

mode
type
category
price
size

我希望我的用户根据上述字段过滤文档,即用户可以尝试通过以下任意字段的组合来过滤结果:

mode=='foo' && type=='bar'
category=='foo' && price>500 && size<50
category=='bar'
...
...

这将导致许多不同的组合可能性。但是,对于字段modecategorytype,用户只能根据相等条件进行过滤,而对于字段pricesize他可以使用范围比较进行过滤。

此外,我还需要功能orderBy以升序和降序使用价格。

因此,对于所有应用的过滤器,firebase查询最多可包含3个相等子句和2个范围比较。显然,这意味着我必须在firebase控制台中创建适当的复合索引,以这种方式查询数据。

一些查询示例如下:

db.where('price', '<', 2000).where('category','==','foo').where('size', '>', 80).orderBy('price', 'desc')
db.where('price', '>', 300).where('type','==','foo').where('mode', '==', 'bar').where('category', '==', 'foo').where('size', '<', 500).orderBy('price')

由于这将导致大量索引消耗存储空间,因此Firebase文档建议 merging indexes for equality clauses

现在我的问题是针对上述情况创建复合索引的最佳方法是什么,以便我可以使用上述任意组合查询数据,同时利用控制台的优势在控制台中创建最少数量的索引Firestore的“合并技术”。

我想知道是否必须创建类似以下的索引:

mode (ascending), price (ascending)
type (ascending), price (ascending)
category (ascending), price (ascending)
size (ascending), price (ascending)

mode (ascending), price (descending)
type (ascending), price (descending)
category (ascending), price (descending)
size (ascending), price (descending)

这里的问题正在测试中,因为测试每个可能的已创建索引的查询非常忙。 因此,我一直在寻找能够确保上述所有可能查询的索引组合。

1 个答案:

答案 0 :(得分:0)

Firestore查询只能包含一个range子句,因此这种查询是不可能的:

category=='foo' && price>500 && size<50