java检索ES返回字段
时间: 2023-07-20 22:43:01 浏览: 118
要在Java中检索Elasticsearch并返回指定的字段,可以使用Elasticsearch Java API中的Search API和Source Filtering。以下是一个简单的例子:
```
SearchRequest searchRequest = new SearchRequest("your-index-name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("your-field-name", "your-search-keyword"));
searchSourceBuilder.fetchSource(new String[] {"field1", "field2"}, null);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
String field1Value = hit.getSourceAsMap().get("field1").toString();
String field2Value = hit.getSourceAsMap().get("field2").toString();
// Do something with the field values
}
```
在上面的示例中,我们使用`fetchSource`方法来指定要返回的字段列表,其中第二个参数为`null`表示不包括任何排除字段。然后,我们使用`getSourceAsMap`方法来获取指定字段的值。
阅读全文