【问题标题】:How to return results where a field starts with a specific letter or letters in Elasticsearch?如何在 Elasticsearch 中以特定字母或字母开头的字段返回结果?
【发布时间】:2017-12-14 16:44:15
【问题描述】:

我有一些类似的数据

"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"
    }
}

所有这些都将返回所有名称,而不仅仅是真正以a开头的名称

有什么想法吗?

【问题讨论】:

  • 您是否为您的索引预定义了任何映射?
  • 它只是一个文本字段。我有last_name.keywordlast_name 用于分析与未分析。但是在last_name.keyword 上运行任何东西都不会返回任何结果

标签: elasticsearch startswith


【解决方案1】:

所以你得到所有结果的原因是因为它是一个 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" }
    }
}

【讨论】:

    猜你喜欢
    • 2014-11-03
    • 1970-01-01
    • 2015-07-14
    • 2019-07-17
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多