如何查询"最近热门帖子" ?使用Firestore ?
我认为它是"最近的"。如果它是在最近4小时内上传的。我认为这是"趋势"。如果有超过2000个赞
我已经试过了:
const MIN_NUMBER_OF_LIKES_FOR_BEING_TRENDING = 2000;
async function getRecentTrendingPosts(
limit = 10,
minimumPostsDate = diffDate(new Date(), 4, "hours"),
) {
const query = firestore
.collectionGroup("userPosts")
.where("date", ">=", minimumPostsDate)
.where("totalLikes", ">=", MIN_NUMBER_OF_LIKES_FOR_BEING_TRENDING)
.orderBy(date, "desc");
const querySnapshot = await query.limit(limit).get();
const posts = await Promise.all(
querySnapshot.docs.map((postDoc) => parsePost(postDoc))
);
return posts;
}
但它不起作用,我很确定这是因为应用了">="到两个不同的字段
在复合查询中,range (<, <=,>,>=)且不等于(!)=, not-in)比较必须对同一字段进行过滤。
还有其他实现这种类型查询的想法吗?
另外,我正在考虑添加
.where("__name__", ">=", uuidv4())
,只是为了增加一定程度的随机性。
不是最好的解决方案,但对我有用:
import _ from "lodash";
const MIN_NUMBER_OF_LIKES_FOR_BEING_TRENDING = 2000;
const MAX_TRENDING_POSTS_TO_RETRIEVE = 10;
async function getTrendingPosts(
currentUserId
limit = MAX_TRENDING_POSTS_TO_RETRIEVE,
) {
const minLikes = _.random(
MIN_NUMBER_OF_LIKES_FOR_BEING_TRENDING,
MIN_NUMBER_OF_LIKES_FOR_BEING_TRENDING * _.random(1, 10)
);
const maxLikes = _.random(
minLikes + 1,
(minLikes + 1) * _.random(1, 100)
);
const query = firestore
.collectionGroup("userPosts")
.where("totalLikes", ">=", minLikes)
.where("totalLikes", "<=", maxLikes)
.orderBy("totalLikes", "desc")
.orderBy("date", "desc");
const querySnapshot = await query.limit(limit).get();
const posts = await Promise.all(
querySnapshot.docs.map((postDoc) => parsePost(postDoc, currentUserId))
);
return posts;
}