对Elasticsearch索引上的“关键字”字段进行汇总搜索

时间:2018-08-05 16:55:22

标签: python elasticsearch elasticsearch-5 elasticsearch-aggregation

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

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

执行此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')

1 个答案:

答案 0 :(得分:1)

即使没有任何特殊映射,您也应该能够在**flights = db.execute(text("SELECT * FROM books WHERE title LIKE :title"), {"title": f"%{title}%"}).fetchall()** **flights = db.execute( text("SELECT * FROM books WHERE title LIKE ('%' || :title || '%')"), {"title": title}).fetchall();** ***NameError: name 'text' is not defined*** 字段上进行汇总。如果您对搜索结果不感兴趣,只需在查询的顶层添加xyz.keyword属性。