[英]Firebase Firestore - Get recent trending posts
How can I query for "recent trending posts" using Firestore?如何使用 Firestore 查询“最近的热门帖子”?
I am considering it as "recent" if it is was uploaded in the last 4 hours.
如果它是在过去 4 小时内上传的,我认为它是“最近的”。 I am considering it as "trending" if it has more than 2000 likes.
如果它有超过 2000 个喜欢,我认为它是“趋势”。
I have tried the following:我尝试了以下方法:
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;
}
But it doesn't work, and I am pretty sure it is because of applying ">=" to two different fields.但它不起作用,我很确定这是因为将 ">=" 应用于两个不同的字段。
In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.
在复合查询中,范围 (<, <=, >, >=) 和不等于 (!=, not-in) 比较必须都过滤同一字段。
Any other idea for implementing this type of query?实现此类查询的任何其他想法?
Also, I was thinking about adding另外,我正在考虑添加
.where("__name__", ">=", uuidv4())
to the query, just to add a degree of randomness.到查询中,只是为了增加一定程度的随机性。
Not the best solution, but works for me:不是最好的解决方案,但对我有用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.