在 Elasticsearch 索引的 "keyword" 字段上进行聚合搜索

Aggregated search on a "keyword" field on an Elasticsearch index

我在 Elasticsearch 上有一个索引,我想在该索引上对被视为分类字段的 text 类型的字段执行聚合。

在索引映射中,我将该字段定义为 keyword,因此我不必使用 fielddata=true,如此处文档中所述:https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html

执行此 HTTP GET 查询时,我没有得到聚合结果,Elasticsearch returns 整个索引(所有完整文档):

GET my_stuff_index/_search
{
  "query" : {
    "constant_score" : {
      "filter" : {
        "exists" : { "field" : "xyz.keyword" }
      }
    }
  },
    "aggs": {
        "my_avg_ratings_report": {
            "terms": {
                "field": "xyz.keyword"
            }
        }
    }

}

如何将 xyz 字段视为分类字段并在聚合中使用它?

为了使用虚拟索引中的一些文档生成最小工作示例,我使用了以下 python 脚本,其中还定义了索引映射:

from elasticsearch import Elasticsearch
from elasticsearch import helpers

my_docs = [
    {"xyz": "foo", "description": "bla bla bla"},
    {"xyz": "foo", "description": "bla bla bla xyz"},
    {"xyz": "bar", "description": "bla bla bla abc"},
    {"xyz": "bar", "description": "bla bla bla 123"},
    {"xyz": "baz", "description": "bla bla bla 456"},
    {"xyz": "qux", "description": "bla bla bla 789"},
]

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

index_mapping = '''
{
  "mappings":{
    "my_stuff_type":{
      "properties":{
          "xyz": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          }
      }
    }
  }
}'''

es.indices.create(index='my_stuff_index', ignore=400, body=index_mapping)

helpers.bulk(es, my_docs, index='my_stuff_index', doc_type='my_stuff_type')

即使没有任何特殊映射,您也应该能够对 xyz.keyword 字段进行聚合。如果您对搜索结果不感兴趣,只需在查询的顶层添加 "size": 0 属性。