为什么这个 firestore 查询需要索引? [英] Why does this firestore query require an index?

查看:24
本文介绍了为什么这个 firestore 查询需要索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有等于运算符的 where() 方法和一个 orderBy() 方法的查询,但我不明白为什么它需要索引.where 方法检查对象(地图)中的值,order by 是一个数字.

I have a query with a where() method with an equality operator and then an orderBy() method and I can't figure out why it requires an index. The where method checks for a value in an object (a map) and the order by is with a number.

文档说

如果您的过滤器具有范围比较(<、<=、>、>=),则您的第一个排序必须在同一字段上

If you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field

所以我会认为相等过滤器会很好.

So I would have thought that an equality filter would be fine.

这是我的查询代码:

this.afs.collection('posts').ref
.where('tags.' + this.courseID,'==',true)
.orderBy("votes")
.limit(5)
.get().then(snap => {
  snap.forEach(doc => {
    console.log(doc.data());
  });
});

这是一个数据库结构的例子

Here is an example of the database structure

推荐答案

为什么这个 Firestore 查询需要索引?

Why does this Firestore query require an index?

您可能已经注意到,Cloud Firestore 中的查询速度非常快,这是因为 Firestore 会自动为您文档中的任何字段创建索引.因此,当您简单地使用范围比较进行过滤时,Firestore 会自动创建所需的索引.如果您还尝试对结果进行排序,则需要另一个索引.这种索引不是自动创建的.你应该自己创建它.这可以通过在您的 Firebase 控制台 中手动创建来完成,或者您会在日志中找到听起来像这样的消息:

As you probably noticed, queries in Cloud Firestore are very fast and this is because Firestore automatically creates an index for any field you have in your document. So when you simply filter with a range comparison, Firestore creates the required index automatically. If you also try to order your results, another index is required. This kind of index is not created automatically. You should create it yourself. This can be done, by creating it manually in your Firebase Console or you'll find in your logs a message that sounds like this:

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

您只需单击该链接或将 URL 复制并粘贴到网络浏览器中,您的索引就会自动创建.

You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.

因此 Firestore 需要一个索引,以便您可以进行非常快速的查询.

So Firestore requires an index so you can have very fast queries.

这篇关于为什么这个 firestore 查询需要索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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