【问题标题】:How to match a phrase in elastic-search with expandable prefix and suffix?如何将弹性搜索中的短语与可扩展的前缀和后缀匹配?
【发布时间】:2017-05-03 10:46:51
【问题描述】:

我们有一个用例,我们想在弹性搜索中匹配短语,但除了短语查询之外,我们还想搜索部分短语。

例子:

搜索短语:“welcome you”或“lcome you”或“welcome yo”或“lcome yo”这应该与包含短语的文档匹配:

“欢迎你”

“我们欢迎你”

“欢迎你”

“我们欢迎你”

即我们希望通过执行带有附加功能的短语查询来维护单词的顺序,该功能向我们返回包含短语作为部分子字符串的结果,并且前缀和后缀可扩展为特定的可配置长度。 在 elastic 中,我发现了类似的 'match_phrase_prefix' 但它只匹配以特定前缀开头的短语。

以d前缀开头的Ex返回结果:

$ curl -XGET localhost:9200/startswith/test/_search?pretty -d '{
    "query": {
        "match_phrase_prefix": {
            "title": {
                "query": "d",
                "max_expansions": 5
            }
        }
    }
}'

有没有什么方法可以让后缀也实现这一点?

【问题讨论】:

    标签: elasticsearch elasticsearch-2.0 elasticsearch-5


    【解决方案1】:

    我强烈建议您查看shingle token filter

    您可以使用自定义分析器定义索引,该分析器利用 shingles 来索引一组后续标记以及标记本身。

    curl -XPUT localhost:9200/startswith -d '{
      "settings": {
          "analysis": {
            "analyzer": {
              "my_shingles": {
                "tokenizer": "standard",
                "filter": [
                  "lowercase",
                  "shingles"
                ]
              }
            },
            "filter": {
              "shingles": {
                "type": "shingle",
                "min_shingle_size": 2,
                "max_shingle_size": 2,
                "output_unigrams": true
              }
            }
          }
      },
      "mappings": {
        "test": {
          "properties": {
            "title": {
              "type": "text",
              "analyzer": "my_shingles"
            }
          }
        }
      }
    }'
    

    例如,we welcome you to 将被索引为以下标记

    • we
    • we welcome
    • welcome
    • welcome you
    • you
    • you to
    • to

    然后你可以索引几个示例文档:

    curl -XPUT localhost:9200/startswith/test/_bulk -d '
    {"index": {}}
    {"title": "welcome you"}
    {"index": {}}
    {"title": "we welcome you"}
    {"index": {}}
    {"title": "welcome you to"}
    {"index": {}}
    {"title": "we welcome you to"}
    '
    

    最后,您可以运行以下查询来匹配以上所有四个文档,如下所示:

    curl -XPOST localhost:9200/startswith/test/_search -d '{
       "query": {
           "match": {"title": "welcome you"}
       }
    }'
    

    请注意,这种方法比 match_phrase_prefix 查询更强大,因为它允许您匹配文本正文中任何位置的后续标记,无论是在开头还是结尾。

    【讨论】:

    • 但是当我搜索“lcome you”之类的内容时,此解决方案无法处理案例,因为它找不到任何标记“lcome”,它是“welcome”的部分字符串。
    • 抱歉,不清楚您是否还想要部分匹配。您可以尝试通过使用 ngram 令牌过滤器来替代 shingle 过滤器或作为它的补充来改进解决方案,这将奏效。
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多