python - 聚合搜索 Elasticsearch 索引上的 "keyword"字段

标签 python elasticsearch elasticsearch-5 elasticsearch-aggregation

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

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

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

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 属性即可。

关于python - 聚合搜索 Elasticsearch 索引上的 "keyword"字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696404/

相关文章:

Python-将嵌套内的列表分配给变量

python - 逐批读取文件中的多行

elasticsearch - 如何将 ignore_unavailable 作为查询参数传递给 elasticsearch 搜索请求?

elasticsearch - Elasticsearch查询match_all

java - spring-data-elasticsearch 中的 XSD 验证错误

ElasticSearch Phrase Suggester 不返回任何结果

elasticsearch - 按字母顺序对关键字建立索引列表VS在Elasticsearch中根本不排序?

python - 如何使 SQS 的速度超过 1000 条消息/秒?

python - Celery重启丢失定时任务

php - 如何在PHP中使用Elasticsearch搜索 "randomize"结果?