【发布时间】:2020-10-20 02:03:29
【问题描述】:
我希望使用 firestore 进行最有效的查询,该查询将填充最喜欢的文章列表并获取由 articleId 和 authorId 表示的相关数据。 例如,假设我们有一个由文章组成的收藏夹列表。收藏夹列表如下所示:
[
{
id: '123',
userId: '456'
articleId: '789',
authorId: '101'
}
]
进行查询会更快吗?首先查询收藏夹列表,然后从 articleIds 数组中查询文章列表,最后从 authorIds 数组中查询作者列表? (所以总共 3 个查询):
const snapshot = await firestore
.collection('favorites')
.where('userId', '==', userId)
.orderBy('created')
.get();
const favorites = [];
snapshot.forEach(doc => {
const favorite = doc.data();
favorites.push(favorite);
});
const articleIds = favorites.map(favorite => favorite.articleId)
const articlesSnapshot = await firestore
.collection('articles')
.where(firestore.FieldPath.documentId(), 'in', articleIds)
.get();
const articles = [];
articlesSnapshot.forEach(doc => {
const article = doc.data();
articles.push(article);
});
const authorIds = favorites.map(favorite => favorite.authorId)
const authorsSnapshot = await firestore
.collection('users')
.where(firestore.FieldPath.documentId(), 'in', authorIds)
.get();
const authors = [];
authorsSnapshot.forEach(doc => {
const author = doc.data();
authors.push(author);
});
return { authors, articles, favorites }
或者我应该遍历收藏列表并进行单独查询以获取单个文章(来自 articleId)和单个作者(来自 authorId)?
我觉得第二个选项会慢很多,因为要进行所有单独的查询。我说的对吗?第一个查询会更高效(更快)吗?
【问题讨论】:
-
一般来说,Firestore 的性能取决于您阅读的文档数量。因此,如果您在两种情况下阅读相同数量的文档,则性能差异可以忽略不计。但这是你可以很容易地进行基准测试的东西,所以你应该这样做。
标签: node.js firebase google-cloud-firestore google-cloud-functions