假设您在索引文档时使用了默认动态映射,那么您的所有 strings 都应该被映射为 text 类型和 keyword 类型。因此,对 keyword 映射的简单 term 查询应该会产生您正在寻找的结果。
例如,使用默认设置创建索引,只需按如下方式完成:
PUT countries-codes
按提供的索引文档将如下所示:
POST countries-codes/event
{
"name": "Albanie",
"alpha_2": "AL",
"alpha_3": "ALB",
"num": "8"
}
现在,我们可以查看索引的映射,看看 Elasticsearch 如何在内部映射字段:
GET countries-codes/_mapping
结果:
{
"countries-codes" : {
"mappings" : {
"event" : {
"properties" : {
"alpha_2" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"alpha_3" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"num" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
}
现在我们只需对 2 字符国家/地区代码的 keyword 映射执行 term 查询,我们将返回一个表示匹配项的文档(或者如果有多个匹配项,所有文档代表那些匹配):
GET countries-codes/_search
{
"query": {
"bool": {
"filter": {
"term": {
"alpha_2.keyword": "AL"
}
}
}
}
}
请注意,这是一个过滤查询,因为您对评分不感兴趣。简而言之,过滤上下文会比查询上下文更快,所以尽可能使用它。更多信息,参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html
这会产生您之前发布的文档,位于 hits 返回数组中:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.0,
"hits" : [
{
"_index" : "countries-codes",
"_type" : "event",
"_id" : "qGDmEWoBqkB-aMRpdfvt",
"_score" : 0.0,
"_source" : {
"name" : "Albanie",
"alpha_2" : "AL",
"alpha_3" : "ALB",
"num" : "8"
}
}
]
}
}
提交的任何不匹配的术语都会产生一个空的 hits 数组。在客户端,您可以只解析出您想要的元素。如果您有非常大的文档或要返回的大量文档,您需要查看source filtering - https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html
例如:
GET countries-codes/_search
{
"_source": "alpha_3",
"query": {
"bool": {
"filter": {
"term": {
"alpha_2.keyword": "AL"
}
}
}
}
}
在返回的 hits 对象中,您会注意到文档中只返回了您想要的结果:
"hits" : {
"total" : 1,
"max_score" : 0.0,
"hits" : [
{
"_index" : "countries-codes",
"_type" : "event",
"_id" : "qGDmEWoBqkB-aMRpdfvt",
"_score" : 0.0,
"_source" : {
"alpha_3" : "ALB"
}
}
]
}
所有示例均使用开发工具/简单 API 调用显示。由于您使用的是 Python,请查看官方维护的 Elasticsearch 库:
Elasticsearch DSL - 建立在较低级别的 Elasticsearch-Py 之上 - https://elasticsearch-dsl.readthedocs.io/en/latest/
Elasticsearch-Py - https://elasticsearch-py.readthedocs.io/en/master/