如何在Elasticsearch中搜索句子的开头和结尾 [英] How to search starting and ending of a sentence in elasticsearch

查看:86
本文介绍了如何在Elasticsearch中搜索句子的开头和结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试搜索以下两种情况

I was trying to search the following two cases

我想搜索一个以特定单词开头的名称.例如:

I want to search a name that starts with particular word. For example:

名称:测试名称

name:名称测试

name:测试名称test

name : test name test

如果我搜索"test",那么它应该只返回"test name"和"test name test".

if I search for "test" then it should return me only "test name" and "test name test".

我想搜索一个以特定单词结尾的名称.例如:

I want to search a name that ends with a particular word. For example:

名称:测试名称

name:名称测试

name:测试名称test

name : test name test

如果我搜索"test",那么它应该只返回"name test"和"test name test"

if I search for "test" then it should return me only "name test" and "test name test" .

任何人都可以帮助我找出Elasticsearch Java API或其他任何搜索方式的查询.

Can anyone help me find out queries in elasticsearch java API or any other way to search it.

弹性搜索版本6.2.1

Elastic search version 6.2.1

我们非常感谢您的帮助.

Any help is really appreciated.

推荐答案

对于情况1,您可以使用 CompletionSuggester .您需要为字段使用特殊的映射才能使用完成提示程序,如下所示:

For case 1, you can use CompletionSuggester. You need a special mapping for a field to use completion suggester, like this:

"mappings": {
"some_index": {
    "properties": {
        "title": {
            "type": "completion"
        }
    }
}}

在代码中,您应该定义建议者,例如:( term 是您的搜索词,"starts"是任意名称):

In the code, you should define the suggester, like this (term is your searchword, "starts" is an arbitrary name):

CompletionSuggestionBuilder completionBuilder = SuggestBuilders.completionSuggestion("title").prefix(term);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("starts", completionBuilder);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.suggest(suggestBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(searchSourceBuilder);

获得搜索响应后,对其进行处理以检索建议:

After you get the search response, process it to retrieve the suggestions:

  Suggest suggest = searchResponse.getSuggest();
  if (suggest == null) {
    return Collections.emptyList();
  } else {
    CompletionSuggestion suggestion = suggest.getSuggestion("starts");
    return suggestion
        .getOptions()
        .stream()
        .map(CompletionSuggestion.Entry.Option::getText)
        .map(Text::toString)
        .collect(Collectors.toList());
  }

这篇关于如何在Elasticsearch中搜索句子的开头和结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆