【问题标题】:Not able to aggregate on nested fields in elasticsearch无法聚合弹性搜索中的嵌套字段
【发布时间】:2015-05-06 07:56:35
【问题描述】:

我已将一个字段设置为嵌套,现在我无法对其进行聚合。 示例文档 -

{
"attributes" : [
{ "name" : "snake" , "type" : "reptile" },
{ "name" : "cow" , "type" : "mamal" }
]
}

属性字段是嵌套的。 以下术语查询不适用于此

{ 
"aggs" : {
"terms" : { "field" : "attributes.name" }
}
}

如何在 elasticsearch 中进行聚合?

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    使用nested aggregation

    作为一个简单的示例,我创建了一个索引,其中包含与您发布的内容相匹配的嵌套属性:

    PUT /test_index
    {
       "mappings": {
          "doc": {
             "properties": {
                "attributes": {
                   "type": "nested",
                   "properties": {
                      "name": {
                         "type": "string"
                      },
                      "type": {
                         "type": "string"
                      }
                   }
                }
             }
          }
       }
    }
    

    然后添加您的文档:

    PUT /test_index/doc/1
    {
       "attributes": [
          { "name": "snake", "type": "reptile" },
          { "name": "cow", "type": "mammal" }
       ]
    }
    

    现在我可以得到"attribute.name"的条款如下:

    POST /test_index/_search?search_type=count
    {
       "aggs": {
          "nested_attributes": {
             "nested": {
                "path": "attributes"
             },
             "aggs": {
                "name_terms": {
                   "terms": {
                      "field": "attributes.name"
                   }
                }
             }
          }
       }
    }
    ...
    {
       "took": 7,
       "timed_out": false,
       "_shards": {
          "total": 1,
          "successful": 1,
          "failed": 0
       },
       "hits": {
          "total": 1,
          "max_score": 0,
          "hits": []
       },
       "aggregations": {
          "nested_attributes": {
             "doc_count": 2,
             "name_terms": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                   {
                      "key": "cow",
                      "doc_count": 1
                   },
                   {
                      "key": "snake",
                      "doc_count": 1
                   }
                ]
             }
          }
       }
    }
    

    这是我使用的代码:

    http://sense.qbox.io/gist/0e3ed9c700f240e523be08a27551707d4448a9df

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      相关资源
      最近更新 更多