我有一些MongoDB集合:
案例:
{
title: { type: String },
text: { type: String }
}
评论:
{
text: { type: String },
story: { type: mongoose.Schema.Types.ObjectId, ref: "Stories" }
}
喜欢:
{
story: { type: mongoose.Schema.Types.ObjectId, ref: "Stories" }
}
此集合由Elasticsearch编制索引。所以我需要通过喜欢和评论来过滤Elasticsearch中的Stories。
示例数据。
Stories:
{
"title": "First story",
"text": "This must be the MOST popular story..."
}
{
"title": "Second story",
"text": "This story is popular too, but not as the first story."
}
{
"title": "Third story",
"text": "This is a unpopular story, because dont have any comment or like"
}
Comments:
{
"title": "Foo",
"story": ObjectId("First Story ID")
}
{
"title": "Foobar",
"story": ObjectId("First Story ID")
}
{
"title": "Bar",
"story": ObjectId("Second Story ID")
}
Likes:
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("First Story ID") }
{ "story": ObjectId("Second Story ID") }
{ "story": ObjectId("Second Story ID") }
{ "story": ObjectId("Third Story ID") }
过滤的结果应该是这样的:
使用Elasticsearch真的可以吗?我怎么能这样呢?
PS。为什么我选择不使用Mongo过滤?因为Mongo显示这种聚合的结果很慢。
PPS。此任务的Mongo聚合代码:
db.getCollection('stories').aggregate([
{$lookup:{from:"comments",localField:"_id", foreignField:"story", as:"comments"}},
{$lookup:{from:"likes",localField:"_id", foreignField:"story", as:"likes"}},
{$project: { title: 1, text: 1,comments:1,likes:1, count: { $add: [ {$size: "$comments"}, {$size: "$likes"} ] } } },
{$sort:{"count":-1}}
])
答案 0 :(得分:0)
你的评分标准是什么?
无论如何,我只是将它实现为两个单独的terms aggregations并在客户端合并结果。应该可以将其建模为parent-child关系,但如果没有显着的上升空间,它会更加复杂。
您可以在第一次查询时获得前10个最受欢迎的故事,然后仅针对这些ID(filtering values with exact values)获取评论聚合。