【问题标题】:Adding additional fields to ElasticSearch terms aggregation向 ElasticSearch 术语聚合添加其他字段
【发布时间】:2016-01-22 23:09:34
【问题描述】:

索引文档如下:

{
  id: 1, 
  title: 'Blah',
  ...
  platform: {id: 84, url: 'http://facebook.com', title: 'Facebook'}
  ...
}

我想要的是按平台计算和输出统计信息。 对于计数,我可以使用以 platform.id 为字段的术语聚合来计数:

aggs: {
  platforms: {
    terms: {field: 'platform.id'}
  }
}

通过这种方式,我收到的统计信息是一个看起来像 {key: 8, doc_count: 162511} 的多个存储桶,正如预期的那样。

现在,我能否以某种方式将 platform.nameplatform.url 添加到这些存储桶中(以获得漂亮的统计数据输出)?我带来的最好的看起来像:

aggs: {
  platforms: {
    terms: {field: 'platform.id'},
    aggs: {
      name: {terms: {field: 'platform.name'}},
      url: {terms: {field: 'platform.url'}}
    }
  }
}

事实上,这很有效,并且在每个存储桶中返回了相当复杂的结构:

{key: 7,
  doc_count: 528568,
  url:
   {doc_count_error_upper_bound: 0,
    sum_other_doc_count: 0,
    buckets: [{key: "http://facebook.com", doc_count: 528568}]},
  name:
   {doc_count_error_upper_bound: 0,
    sum_other_doc_count: 0,
    buckets: [{key: "Facebook", doc_count: 528568}]}},

当然,可以从这个结构中提取平台的名称和url(如bucket.url.buckets.first.key),但是有没有更简洁的方法来完成这项任务?

【问题讨论】:

  • 您找到解决问题的方法了吗?我现在也面临同样的情况:(
  • 我把它贴在下面作为我自己的“接受”答案:)

标签: elasticsearch


【解决方案1】:

似乎最好的表达意图的方式是top hits聚合:“从每个聚合组中只选择一个文档”,然后从中提取平台:

aggs: {
  platforms: {
    terms: {field: 'platform.id'},
    aggs: {
      platform: {top_hits: {size: 1, _source: {include: ['platform']}}}
  }
}

这样,每个 bucked 将如下所示:

{"key": 7,
  "doc_count": 529939,
  "platform": {
    "hits": {
      "hits": [{
       "_source": {
        "platform": 
          {"id": 7, "name": "Facebook", "url": "http://facebook.com"}
        }
      }]
    }
  },
}

这有点太深了(和 ES 一样),但很干净:bucket.platform.hits.hits.first._source.platform

【讨论】:

  • @moeinrahimi 不是整个文档,而是包含与键 platform 对应的单个条目的子集
【解决方案2】:

如果您不一定需要获取 platform.id 的值,则可以使用单个聚合而不是使用连接两个字段 nameurlscript

aggs: {
  platforms: {
    terms: {script: 'doc["platform.name"].value + "," + doc["platform.url"].value'}
  }
}

【讨论】:

  • 是的,script 的解决方案非常明显。而且对我来说也很丑。只是检查是否有更清洁的东西。
  • 很确定可以围绕 scripted metric 聚合做一些事情。我稍后会尝试,但你可以试一试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 2018-10-18
  • 2014-07-09
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多