21

我如何编写一个 Elasticsearch 术语聚合,按整个术语而不是单个令牌分割存储桶?例如,我想按州聚合,但以下将 new、york、jersey 和 california 作为单独的桶返回,而不是按预期将 New York、New Jersey 和 California 作为桶返回:

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 只有一个区别:在我的例子中,城市字段是一个数组.

示例对象:

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

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

我的映射:

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

我试图用“字符串”替换“对象”,但这也不起作用。

4

1 回答 1

17

我认为您所缺少的只是"states.raw"聚合(请注意,由于未指定分析器,因此"states"使用标准分析器分析该字段;子字段"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

于 2015-11-16T18:06:49.117 回答