GET user-info/_search { "query": { "match": { "name": "hang si" } } } 查询结果: ... "hits" : [ { "_index" : "user-info", "_type" : "_doc", "_id" : "1", "_score" : 1.5037103, "_source" : { "id" : 1, "name" : "zhang san" } }, { "_index" : "user-info", "_type" : "_doc", "_id" : "2", "_score" : 1.5037103, "_source" : { "id" : 2, "name" : "li si" } } ] 转为java代码
时间: 2023-07-03 13:09:30 浏览: 73
以下是使用Java High Level REST Client进行Elasticsearch查询的示例代码:
```
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
SearchRequest searchRequest = new SearchRequest("user-info");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", "hang si");
searchSourceBuilder.query(matchQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
String index = hit.getIndex();
String id = hit.getId();
float score = hit.getScore();
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
// Do something with the search hit...
}
client.close();
```
其中,我们首先创建了一个`RestHighLevelClient`实例,指定了Elasticsearch服务器的主机和端口。
然后,我们创建了一个`SearchRequest`实例,指定了我们要查询的索引名称。接着,我们通过`SearchSourceBuilder`构建查询条件,这里使用了`MatchQueryBuilder`来进行匹配查询。
然后,我们将查询条件设置到`SearchRequest`中,并执行查询。查询结果包含在`SearchResponse`对象中,我们可以从中获取`SearchHits`对象,遍历其中的`SearchHit`对象,获取相关信息,如索引名称、文档ID、文档得分等。最后,我们关闭`RestHighLevelClient`实例。
阅读全文