ElasticSearch聚合嵌套字段

时间:2015-05-18 18:22:13

标签: elasticsearch

我有一个带有映射的产品存储库:

settings do
  mapping do
    indexes :name
    indexes :vendor_id,   type: 'integer'
    indexes :category_id, type: 'integer'

    indexes :spec_entries, type: 'nested' do
      indexes :spec_id,     type: 'integer'
      indexes :value_id,    type: 'integer'
      indexes :name,        index: 'no'
      indexes :description, index: 'no'
      indexes :value,       index: 'no'
    end
  end
end

规格条目是产品规格(例如:Fork:Air),其中Fork是名称,Air是值。还有规范ID,规范值ID和规范说明。

我需要获得这样的聚合结果:

[
...
{
  id: 335,
  name: "Fork",
  description: "There are few common types of fork — elastomer, oil and air",
  count: 30,
  values: [{
    id: 645,
    name: "Elastomer",
    count: 17
  }, {
    id: 643,
    name: "Oil",
    count: 10
  }, {
    id: 649,
    name: "Air",
    count: 3
  }, ]
},
...
]

规格和值应按计数排序。

我需要使用哪种类型的聚合?

1 个答案:

答案 0 :(得分:0)

您希望使用nested聚合(因为spec_entries具有nested类型,然后termsspec_entries.name的{​​{1}}聚合} sub-aggregation来获得顶级嵌套top_hits。像这样的东西应该这样做:

spec_entries

这会产生非常接近你期望的东西:

{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "spec_names": {
      "nested": {
        "path": "spec_entries"
      },
      "aggs": {
        "names": {
          "terms": {
            "field": "spec_entries.name"
          },
          "aggs": {
            "top_entries": {
              "top_hits": {
                "field": "spec_entries.value"
              }
            }
          }
        }
      }
    }
  }
}

请注意,使用{ ... "aggregations" : { "spec_names" : { "doc_count" : 1, "names" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : "fork", <-------- The spec_entries name "doc_count" : 1, "top_values" : { "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "tests", "_type" : "test1", "_id" : "1", "_nested" : { "field" : "spec_entries", "offset" : 0 }, "_score" : 1.0, "_source":{ <-------- For each name, the top spec_entries content (value, id, desc, etc) "name":"Fork", "value":"Air", "description":"desc", "spec_id":1, "value_id":1 } } ] } } } ] } } } } 聚合作为top_hits聚合的子聚合只能使用from ES 1.5 onward