2017-05-03 41 views
0

我们有一个用例,我们想在弹性搜索中匹配短语,但除了短语查询外,我们还想搜索部分短语。如何在弹性搜索中使用可扩展前缀和后缀匹配短语?

例子:

搜索短语:“欢迎你”或“lcome你”或“欢迎哟”或“lcome哟”这应该与包含文件短语:

“欢迎你”

“我们欢迎你”

“欢迎您”

“我们欢迎你”

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

防爆返回的结果:

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

有什么办法,我可以做到这一点的后缀呢?

回答

1

我强烈建议您查看shingle token filter

您可以使用自定义分析器来定义索引,该分析器利用带状疱疹除了标记本身之外还将一组后续标记索引到一起。

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

请注意,这种方法比更强大查询,因为它允许您在文本正文的任何​​位置匹配随后的令牌,无论是在开始还是结束。

+0

但是,当我搜索诸如“lcome you”之类的东西时,此解决方案将不会处理这种情况,因为它不会找到任何令牌“lcome”,它是部分“welcome”字符串。 – user2530619

+1

对不起,这并不清楚你还想要部分匹配。你可以尝试改进解决方案,通过使用'ngram'标记过滤器来代替木瓦或者作为它的补充,这样就可以解决问题。 – Val