在Firestore中,如何在不为每个键创建索引的情况下执行涉及地图中的键的复合查询? [英] In Firestore, how can you do a compound query involving a key in a map without creating an index for every key?
问题描述
在Firestore中,如何在不为每个键创建索引的情况下执行涉及地图中键的复合查询?
In Firestore, how can you do a compound query involving a key in a map without creating an index for every key?
例如,考虑一个包含的集合博客文章,每篇博文都有类别。
For example, consider a collection which holds blog posts, and each blog post has categories.
Post {
title: ..
...
categories: {
cats: true
puppies: true
}
}
为了以分页方式查询特定类别中的帖子,我们将执行以下操作:
In order to query posts in a particular category in a paginated way, we would do something like this:
let query = db.collection(`/posts`)
.where(`categories.${categoryId}`, '==', true)
.orderBy('createdAt')
.startAfter(lastDate)
.limit(5);
但似乎这需要一个综合指数(类别。<每个类别的categoryId>
和 createdAt
)。有什么方法吗?
But it seems that this would require a composite index (categories.<categoryId>
and createdAt
) for every single category. Is there any way around this?
在我的情况下,为每个类别创建复合索引是不可行的,因为类别是用户生成的,并且很容易超过200 (Firestore中复合索引的限制)。
In my case, it isn't feasible to create composite indices for every category since categories are user-generated, and could easily exceed 200 (the limit for composite indices in Firestore).
推荐答案
这可以通过将每个类别的值设置为您想要的值来实现排序。 Firestore有一个涵盖此内容的指南。
This is doable by setting the value of each category to what you want to sort on. Firestore has a guide that covers this.
Post {
title: ..
...
categories: {
cats: createdAt
puppies: createdAt
}
}
let query = db.collection(`/posts`)
.where(`categories.${categoryId}`, '>', 0)
.orderBy(`categories.${categoryId}`)
.startAfter(lastDate)
.limit(5);
这篇关于在Firestore中,如何在不为每个键创建索引的情况下执行涉及地图中的键的复合查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!