【问题标题】:ElasticSearch wildcard not returning when value has special characters当值具有特殊字符时,ElasticSearch 通配符不返回
【发布时间】:2021-07-08 01:09:32
【问题描述】:

我有一个弹性搜索服务,当您输入文本输入然后填充表格时,它会获取该服务。对于所有字母数字值,但不是特殊字符(特别是连字符),搜索工作正常(返回过滤数据)。例如,对于国家/地区 Timor-Leste,如果我将 Timor 作为术语传入,我会得到结果,但只要添加连字符 (Timor-),就会得到一个空数组响应。

const queryService = {
  search(tableName, field, term) {
    // If there is no search term, run the wildcard search with 20 values
    // for the smaller lists to be pre-populated, like "Gender"
    return `
{
  "size": ${term ? 200 : 20},
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "tablename": "${tableName}"
          }
        },
        {
          "wildcard": {
            "${field}": {
              "value": "${term ? `*${term.trim()}*` : '*'}",
              "boost": 1.0,
              "rewrite": "constant_score"
            }
          }
        }
      ]
    }
  }
}
`;
  },
};

有没有办法可以修改我的通配符请求以允许使用连字符?我在这里看到的另一个回复建议使用"analyze_wildcard": true,但没有奏效。我还尝试通过在每个带有.replace 的连字符前添加\ 来手动转义。

【问题讨论】:

    标签: amazon-web-services elasticsearch wildcard


    【解决方案1】:

    这一切都归结为 Elasticsearch analyzers

    默认情况下,所有text 字段都将通过standard analyzer 运行,例如:

    GET _analyze/
    {
      "text": ["Timor-Leste"],
      "analyzer": "standard"
    }
    

    这会将您的输入小写,去除任何特殊字符,并生成标记:

    ["timor", "leste"]
    

    如果您想放弃此默认流程,请添加 .keyword 映射:

    PUT your-index/
    {
      "mappings": {
        "properties": {
          "country": {
            "type": "text",
            "fields": {             <---
              "keyword": {          
                "type": "keyword"
              }
            }
          }
        }
      }
    }
    

    然后重新索引您的文档,并在使用新创建的 .keyword 字段动态构造 wildcard 查询时,确保正确转义连字符(和所有其他特殊字符):

    POST your-index/_search
    {
      "query": {
        "wildcard": {
          "country.keyword": {
            "value": "*Timor\\-*"    <---
          }
        }
      }
    }
    

    【讨论】:

    • 这个@Apswak 运气好吗?
    猜你喜欢
    • 2021-08-01
    • 2016-09-26
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多