Elasticsearch通过数组中的字符串对术语进行聚合

时间:2015-11-16 17:40:34

标签: arrays elasticsearch aggregation buckets

如何编写Elasticsearch术语聚合,将整个术语而不是单个标记拆分为多个?例如,我想按州聚合,但以下将新的,约克,泽西和加利福尼亚作为单独的桶,而不是纽约,新泽西和加利福尼亚作为预期的桶:

curl -XPOST "http://localhost:9200/my_index/_search" -d'
{
    "aggs" : {
        "states" : {
            "terms" : { 
                "field" : "states",
                "size": 10
            }
        }
    }
}'

我的用例就像这里描述的那样 https://www.elastic.co/guide/en/elasticsearch/guide/current/aggregations-and-analysis.html 只有一个区别: 在我的情况下,city field是一个数组。

示例对象:

{
    "states": ["New York", "New Jersey", "California"]
}

似乎建议的解决方案(将字段映射为not_analyzed)对数组不起作用。

我的映射:

{
    "properties": {
        "states": {
            "type":"object",
            "fields": {
                "raw": {
                    "type":"object",
                    "index":"not_analyzed"
                }
            }
        }
    }
}

我试图替换"对象" by" string"但这也不起作用。

1 个答案:

答案 0 :(得分:10)

我认为您在聚合中遗漏的所有内容都是"states.raw"(请注意,由于未指定分析器,因此使用standard analyzer分析"states"字段; -field "raw""not_analyzed")。虽然您的映射可能也值得关注。当我尝试对ES 2.0进行映射时,我遇到了一些错误,但这很有效:

PUT /test_index
{
   "mappings": {
      "doc": {
         "properties": {
            "states": {
               "type": "string",
               "fields": {
                  "raw": {
                     "type": "string",
                     "index": "not_analyzed"
                  }
               }
            }
         }
      }
   }
}

然后我添加了几个文档:

POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"states":["New York","New Jersey","California"]}
{"index":{"_id":2}}
{"states":["New York","North Carolina","North Dakota"]}

此查询似乎符合您的要求:

POST /test_index/_search
{
    "size": 0, 
    "aggs" : {
        "states" : {
            "terms" : { 
                "field" : "states.raw",
                "size": 10
            }
        }
    }
}

返回:

{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "states": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "New York",
               "doc_count": 2
            },
            {
               "key": "California",
               "doc_count": 1
            },
            {
               "key": "New Jersey",
               "doc_count": 1
            },
            {
               "key": "North Carolina",
               "doc_count": 1
            },
            {
               "key": "North Dakota",
               "doc_count": 1
            }
         ]
      }
   }
}

这是我用来测试它的代码:

http://sense.qbox.io/gist/31851c3cfee8c1896eb4b53bc1ddd39ae87b173e