Is it possible to query over specific document ids in firestore?

huangapple go评论81阅读模式
英文:

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)

但是我必须在这些特定项目中使用过滤器和分页。所以我需要创建一个查询,以便稍后在同一个查询上使用StartAfterLimitWhere。在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.

huangapple
  • 本文由 发表于 2023年7月7日 01:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定