【问题标题】:Elasticsearch aggregation by multiple indices通过多个索引进行 Elasticsearch 聚合
【发布时间】: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") }

过滤的结果应该是这样的:

  1. 第一个故事(4 个赞,2 个 cmets)
  2. 第二个故事(2 个赞,1 条评论)
  3. 第三个故事(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


    【解决方案1】:

    你的评分标准是什么?

    无论如何,我只是将其实现为两个独立的terms aggregations,并在客户端合并结果。应该可以将其建模为parent-child 关系,但如果没有显着的优势,它会复杂得多。

    您可以在第一次查询时获得前 10 个最喜欢的故事,然后仅获得这些 ID (filtering values with exact values) 的评论聚合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2015-12-20
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      相关资源
      最近更新 更多