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

查看:25
本文介绍了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)

会抛出错误:

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

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-2017products-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天全站免登陆