英文:
Is it possible to query over specific document ids in firestore?
问题
所以,我有一个包含projectId和userId的userProject集合。我通过以下方式获取特定用户的所有项目:
query := db.Collection("userProject").Where("user_id", "==", userId)
现在,我获取了相关用户的projectIds。但是由于可能有很多项目id(>30),我不能像下面这样使用"in"运算符:
query := db.Collection("project").Where("id", "in", projectIds)
我能想到的一个解决方案是使用这些id创建docRefs:
var docRefs []*firestore.DocumentRef
for _, id := range projectIds {
docRefs = append(docRefs, db.Collection("project").Doc(id))
}
然后使用以下代码:
db.GetAll(context.Background(), docRefs)
但是我必须在这些特定项目中使用过滤器和分页。所以我需要创建一个查询,以便稍后在同一个查询上使用StartAfter
、Limit
和Where
。在Firestore中,我该如何用Golang实现这个目标呢?
英文:
So, I have userProject collection with projectId and userId. I get all projects of some specific user by using
query = db.Collection("userProject").Where("user_id","==",userId)
Now, I get projectIds of the related user. But since there can be many project ids(>30), I can't use "in" operator like
query = db.Collection("project").Where("id","in",projectIds)
One solution I can think of is making docRefs with those ids
for _, id := range projectIds {
docRefs = append(docRefs, db.Collection("project").Doc(id))
}
and then use
db.GetAll(context.Background(), docrefs)
But i have to use filters and pagination in those specific projects. So I need to make a query, so that I can later use StartAfter
, Limit
and Where
on same query. How can i achieve that in firestore with golang?
答案1
得分: 1
根据你当前的架构,你想要做的事情是不可能的(对一个大型已知项目列表进行分页)。
最简单的方法是将用户ID复制到项目集合中的文档中,并在查询时仅过滤用户ID。在 NoSQL 类型的数据库中,像这样复制数据(去规范化)是非常常见的,以便实现更高效的查询。
英文:
With your current schema, what you're trying to do isn't possible (pagination on a large, known list of items).
The easiest thing to do is duplicate the user id into the documents in the projects collection, and just query that collection filtering on user id. Duplicating data like this (denormalization) is very common in nosql type databases in order to enable more efficient queries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论