【发布时间】:2017-06-23 12:16:26
【问题描述】:
我有一些 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 中按 likes 和 cmets 过滤 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") }
过滤的结果应该是这样的:
- 第一个故事(4 个赞,2 个 cmets)
- 第二个故事(2 个赞,1 条评论)
- 第三个故事(1 个赞)
使用 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}}
])
【问题讨论】:
标签: mongodb elasticsearch aggregation-framework