聚合elasticsearch中的值列表

时间:2015-04-15 13:29:27

标签: elasticsearch

{
    ...
    "shirt_sizes":["XL","L","M","S"]
    ...
}

如何在elasticsearch中创建shirt_size字段的聚合?

1 个答案:

答案 0 :(得分:1)

假设我正确理解您的问题,您需要使用terms aggregation。您可能还希望"shirt_sizes"字段为not_analyzed

作为一个简单的例子,我设置了一个带有未分析字段的索引,并添加了几个文档:

PUT /test_index
{
   "mappings": {
      "doc": {
         "properties": {
            "shirt_sizes": {
               "type": "string",
               "index": "not_analyzed"
            }
         }
      }
   }
}

POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"shirt_sizes":["XL","L","M","S"]}
{"index":{"_id":2}}
{"shirt_sizes":["L","M","S","XS"]}

然后我可以通过简单的聚合来恢复所有尺寸:

POST /test_index/_search?search_type=count
{
    "aggs": {
        "shirt_sizes_terms": {
            "terms": {
                "field": "shirt_sizes"
            }
        }
    }
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "shirt_sizes_terms": {
         "buckets": [
            {
               "key": "L",
               "doc_count": 2
            },
            {
               "key": "M",
               "doc_count": 2
            },
            {
               "key": "S",
               "doc_count": 2
            },
            {
               "key": "XL",
               "doc_count": 1
            },
            {
               "key": "XS",
               "doc_count": 1
            }
         ]
      }
   }
}

以下是我使用的代码:

http://sense.qbox.io/gist/9d759c95c8794be7786b0248f58bfdec6da7510f