我在Spring Boot应用程序中使用Elasticsearch Java rest高级客户端。我已经使用BulkRequest成功索引了数据。但是,当我想实施搜索时,我无法这样做。我正在使用SearchRequest构建搜索查询。在我的QueryBuilders中,我使用multiMatchQuery在多个文件上搜索关键字。以下是我正在尝试的附加代码:-
public List<POJOClass> searchByKeyword(String keyword) throws IOException {
SearchRequest searchRequest = new SearchRequest("indexName");
searchRequest.types("indexType");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword)
.field("field1")
.field("field2")
.field("field3")
.field("field4");
searchSourceBuilder.query(queryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
List<POJOClass> list= new ArrayList<>();
for(SearchHit hit : searchHits) {
list.add(objectMapper.convertValue(hit.getSourceAsMap(), POJOClass.class));
}
return list;
}
以下是当我调用传递关键字的控制器方法时由QueryBuilder形成的查询:-
curl -XGET "127.0.0.1:9193/search?keyword=KEYWORD"
{
"multi_match" : {
"query" : "KEYWORD",
"fields" : [
"field1^1.0",
"field2^1.0",
"field3^1.0",
"field4^1.0",
],
"type" : "best_fields",
"operator" : "OR",
"slop" : 0,
"prefix_length" : 0,
"max_expansions" : 50,
"zero_terms_query" : "NONE",
"auto_generate_synonyms_phrase_query" : true,
"fuzzy_transpositions" : true,
"boost" : 1.0
}
}
通过REST控制器调用此方法后,SearchResponse方法将返回一个空数组。结果如下:-
{"took":74,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":0,"relation":"eq"},"max_score":null,"hits":[]}}
当我通过传递id使用简单curl来查询时,它会返回结果。例如-
curl -XGET 127.0.0.1:9200/indexName/indexType/id