首页 > 解决方案 > 如何在弹性搜索中部分匹配通配符查询与多个单词?

问题描述

假设文档文本是 This is a sample text to show how the search results works,我的查询字符串是mple tex. 我希望这个查询字符串匹配文本,因为它部分匹配sample text.

我如何在弹性搜索中做到这一点?ES中可以进行很多搜索吗?

我目前使用的是 match_phrase 查询

"query": {"match_phrase": {"description": "mple tex"}},

标签: elasticsearchsearchelastic-stackelasticsearch-dslelasticsearch-query

解决方案


您要查找的内容称为中缀搜索,可以使用ngram 标记过滤器轻松完成,请参阅下面的完整工作示例,这比通配符搜索要好,并且不使用query string不推荐用于搜索框的搜索框,如官方文档中提到。

因为它会针对任何无效语法返回错误,所以我们不建议对搜索框使用 query_string 查询。

索引定义

{
    "settings": {
        "analysis": {
            "filter": {
                "autocomplete_filter": {
                    "type": "ngram",
                    "min_gram": 1,
                    "max_gram": 10
                }
            },
            "analyzer": {
                "autocomplete": {
                    "type": "custom",
                    "tokenizer": "standard",
                    "filter": [
                        "lowercase",
                        "autocomplete_filter"
                    ]
                }
            }
        },
        "index.max_ngram_diff": 10
    },
    "mappings": {
        "properties": {
            "title": {
                "type": "text",
                "analyzer": "autocomplete",
                "search_analyzer": "standard"
            }
        }
    }
}

索引您的示例文档

{
    "title":"This is a sample text to show how the search results works"
}

** 搜索您的文字**

{
   "query": {
      "match": {
         "title": {
            "query": "mple tex"
         }
      }
   }
}

带分数的搜索结果

 "max_score": 0.9168506,
        "hits": [
            {
                "_index": "my-index",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.9168506,
                "_source": {
                    "title": "This is a sample text to show how the search results works"
                }
            }
        ]

注意:请参考我的详细回答,了解如何根据功能和非功能需求以及权衡取舍选择最佳自动完成方法


推荐阅读