首页 > 解决方案 > 带空格的 Elasticsearch 术语不返回任何结果

问题描述

无论大小写如何,我都想匹配确切的文本。我想要的作品

    GET elastic_org/_search
{
  "query": {
    "match": {
      "registeredName": {
        "minimum_should_match": "100%",
        "query": "prop org"
      }
    }
  }
}

但是我使用的库https://github.com/olivere/elastic/不支持最低应该匹配

我正在尝试term查询

GET elastic_org/_search
{
  "query": {
   "term": {
     "registeredName": "Prop org" //also tried prop org
   }
  }
}

我没有得到任何结果。我尝试了上面的查询,nospace得到了结果。

如何在不区分大小写和空格的情况下获得精确匹配?

索引映射:

{
  "elastic_org" : {
    "mappings" : {
      "properties" : {
       
        "id" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        
        "registeredName" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
        
      }
    }
  }
}

标签: elasticsearch

解决方案


您可以将case_insensitive参数与术语查询一起使用。这个参数是在 elasticsearch 7.10.0 版本中引入的

{
  "query": {
    "term": {
      "registeredName.keyword": {
        "value": "prop org",
        "case_insensitive": true
      }
    }
  }
}

更新1:

术语查询返回与搜索词完全匹配的文档。使用术语查询时,text不应使用类型字段。

根据您的索引映射,您需要将 .keyword 添加到该registeredName字段。这使用关键字分析器而不是标准分析器(注意字段后的“.keyword” registeredName)。

更新 2:

如果不想使用case_insensitive参数,可以使用小写过滤器。这将确保在索引和搜索之前所有术语都是小写的

添加带有索引数据、映射、搜索查询和搜索结果的工作示例

索引映射:

{
  "settings": {
    "analysis": {
      "normalizer": {
        "my_normalizer": {
          "type": "custom",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "registeredName": {
        "type": "keyword",
        "normalizer": "my_normalizer"
      }
    }
  }
}

指数数据:

{
  "registeredName": "Prop org"
}

搜索查询:

{
  "query": {
    "term": {
      "registeredName": "prop org"
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "67716203",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.2876821,
        "_source": {
          "registeredName": "Prop org"
        }
      }
    ]

推荐阅读