gpt4 book ai didi

spring - 如何使用 spring-data-elasticsearch 创建建议查询?

转载 作者:行者123 更新时间:2023-12-02 22:49:01 24 4
gpt4 key购买 nike

我想建立一个建议查询,如下所述:
https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-suggesters.html#search-suggesters

{
"query" : {
...
},
"suggest" : {
...
}
}

我如何使用 spring-data-elasticsearch 做到这一点?我在 NativeSearchQueryBuilder 类中找不到此类查询的任何 setter 。

我不想使用原生 json,因为在使用构建器模式构建复杂查询时它会让人不舒服。

最佳答案

举个简短​​的例子 - 在 sample 上有以下映射索引和 test类型:

 "test": {
"properties": {
"description": {"type": "keyword"}
}
}

和索引的文档:
{ "description": "blue sky"}

我想咨询一下:
{
"query" : {
"match": {
"description": "blue sky"
}
},
"suggest" : {
"my-suggest-1" : {
"text" : "blue sk",
"term" : {
"field" : "description"
}
}
}
}

在 Java API 中,您需要向 SearchRequestBuilder 添加 bool 查询和建议:
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery ("description", "blue sky"));

SuggestionBuilder suggestionBuilder =
new TermSuggestionBuilder("description").text("blue sk");
SuggestBuilder suggestion =
new SuggestBuilder().addSuggestion("my-suggest-1", suggestionBuilder);

SearchRequestBuilder builder = client.prepareSearch("sample")
.setTypes("test")
.setQuery(boolQuery)
.suggest(suggestion);

SearchResponse searchResponse;
try {
searchResponse = builder.execute().get();

for (SearchHit hit : searchResponse.getHits().getHits()) {
LOG.info("Result: " + hit.getSourceAsString());
}
} catch (InterruptedException | ExecutionException e) {
LOG.error("Exception while executing query {}", e);
}

当您调试 searchResponse 对象时,它看起来像这样:
{
"took":2,
...,
"hits":{
"total":1,
"max_score":0.2876821,
"hits":[
{
"_index":"sample",
"_type":"test",
"_id":"AV1b42zWa7i_qjvIODcL",
"_score":0.2876821,
"_source":{
"description":"blue sky"
}
}
]
},
"suggest":{
"my-suggest-1":[
{
"text":"blue sk",
"offset":0,
"length":7,
"options":[
{
"text":"blue sky",
"score":0.85714287,
"freq":1
}
]
}
]
}
}

关于spring - 如何使用 spring-data-elasticsearch 创建建议查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com