Firestore多范围查询 [英] Firestore multiple range query

查看:84
本文介绍了Firestore多范围查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些汽车,我想按price范围和year范围过滤它们.我知道由于性能原因,Firestore受到严格限制,所以类似:

Let's say I have a collection of cars and I want to filter them by price range and by year range. I know that Firestore has strict limitations due performance reasons, so something like:

db.collection("products")
  .where('price','>=', 70000)
  .where('price','<=', 90000)
  .where('year','>=', 2015)
  .where('year','<=', 2018)

将引发错误:

无效的查询.不等式(<,< =,>或> =)的所有过滤器都必须位于同一字段上.

Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field.

那么,在没有本地数据管理的情况下还有其他方法可以执行这种查询吗?也许是某种索引或棘手的数据组织?

So is there any other way to perform this kind of query without local data managing? Maybe some kind of indexing or tricky data organization?

推荐答案

错误消息和文档对此非常明确:Firestore查询只能在单个字段上执行范围过滤.由于您尝试同时过滤priceyear上的范围,因此在单个Firestore查询中是不可能的.

The error message and documentation are quite explicit on this: a Firestore query can only perform range filtering on a single field. Since you're trying to filter ranges on both price and year, that is not possible in a single Firestore query.

有两种常见的解决方法:

There are two common ways around this:

  1. 对查询中的一个字段以及客户端代码中的另一个字段执行过滤.
  2. 以某种方式将两个范围的值组合到单个字段中,以使您的用例具有单个字段.这是非常重要的,我所知道的这种组合的唯一成功示例是使用地理哈希值过滤纬度和经度.

鉴于两者在工作量上的差异,我建议选择第一个选项.

Given the difference in effort between these two, I'd recommend picking the first option.

第三个选择是对数据进行不同的建模,以便更轻松地实现用例.最直接的实现方法是将2015-2018年的所有产品放到一个集合中.然后,您可以使用db.collection("products-2015-2018").where('price','>=', 70000).where('price','<=', 90000)查询该集合.

A third option is to model your data differently, as to make it easier to implement your use-case. The most direct implementation of this would be to put all products from 2015-2018 into a single collection. Then you could query that collection with db.collection("products-2015-2018").where('price','>=', 70000).where('price','<=', 90000).

更通用的选择是将产品存储在每年的集合中,然后执行4个查询以获取所需的结果:每个集合products-2015products-2016products-2017中的一个和products-2018.

A more general alternative would be to store the products in a collection for each year, and then perform 4 queries to get the results you're looking for: one of each collection products-2015, products-2016, products-2017, and products-2018.

我建议阅读有关复合查询及其限制的文档,并观看有关Cloud Firestore查询的视频.

这篇关于Firestore多范围查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆