如何 return 结果字段以 Elasticsearch 中的一个或多个特定字母开头?

How to return results where a field starts with a specific letter or letters in Elasticsearch?

我有一些数据,例如

"last_name": "AA-WEST"
"last_name": "VANDER AA"
"last_name": "ARENDES-AA"

我试图只获取以 a 开头的名称,即 AA-WESTARENDES-AA

我试过了

"match": {
    "last_name": {
        "query": "a",
        "operator": "and"
    }
}

"prefix": {
    "last_name": { "value" : "a" }
}

"match_phrase_prefix": {
    "last_name.keyword": {
        "query": "a"
    }
}

所有这些都将 return 所有名称,不仅真正以 a

开头

有什么想法吗?

所以你得到所有结果的原因是因为它是一个 text 字段,VANDER AA 将转换为两个标记。你可以试试:

POST http://{esUri}/_analyze HTTP/1.1
Content-type: application/json

{
   "tokenizer": "standard",
   "text":      "VANDER AA"
}

为避免这种情况,您可以将类型定义为关键字,然后使用

{ 
    "query": {
        "prefix" : { "last_name" : "A" }
    }
}

但我猜这不是您要查找的内容,因为您希望查询不区分大小写。为此,您应该为您的字段定义 normalizer,这将在索引之前自动将您的数据转换为小写。您应该从定义索引开始

PUT http://{esAddress}/indexname HTTP/1.1
{
  "settings": {      
    "analysis": {
      "normalizer": {
        "lowercase_normalizer": {
          "type": "custom",
          "char_filter": [],
          "filter": ["lowercase"]
        }
      }     
    }
  },
  "mappings": {
    "yourtype": {
      "properties": {
        "last_name": {
          "type": "keyword",
          "doc_values": true,
          "normalizer": "lowercase_normalizer"
        }
      }
    }
  }
}

那么前缀查询会给你恰好两个结果:

{ 
    "query": {
        "prefix" : { "last_name" : "a" }
    }
}