我想建立一个像这里描述的建议查询: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-suggesters.html#search-suggesters
{
"query" : {
...
},
"suggest" : {
...
}
}
我如何使用spring-data-elasticsearch做到这一点?我在NativeSearchQueryBuilder类中找不到任何这种查询的setter。
我不想使用原生json,因为使用构建器模式构建复杂查询时会感到不舒服。
答案 0 :(得分:3)
使用简短示例 - 在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
}
]
}
]
}
}