在 Firestore 中,如何在不为每个键创建索引的情况下执行涉及映射中键的复合查询? [英] In Firestore, how can you do a compound query involving a key in a map without creating an index for every key?

查看:11
本文介绍了在 Firestore 中,如何在不为每个键创建索引的情况下执行涉及映射中键的复合查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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);

但这似乎需要为每个单独的类别创建一个复合索引(categories.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屋!

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