1

我想建一个建议者查询喜欢这里描述: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-suggesters.html#search-suggesters如何使用spring-data-elasticsearch创建建议者查询?

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

我怎样才能做到这一点与弹簧数据elasticsearch?我在NativeSearchQueryBuilder类中找不到这种查询的setter。

我不想使用本地json,因为在使用构建器模式构建复杂查询时会感到不舒服。

+1

使用'ElasticsearchTemplate.suggest()'和传递一个'SuggestBuilder'您可以创建一个提示查询。 – Val

+0

@Val如果我需要与我的问题示例中描述的查询相结合的提示,该怎么办?我需要结合同一级别的建议进行查询。 – whitenexx

回答

1

随着短的例子 - 具有以下对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中,您需要添加bool查询和sug GESTION到SearchRequestBuilder

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 
       } 
      ] 
     } 
     ] 
    } 
}