我正在使用Elasticcsearch 7.3。我只想从我的索引中获取使用 JAVA API 的所有文档的两条记录。我正在使用以下代码,但它返回空对象。
RestHighLevelClient client;
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.fetchSource("recipe_ID,recipe_url", null);
sourceBuilder.from(0);
SearchRequest searchRequest = new SearchRequest("recipes");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit searchHit = searchResponse.getHits().getAt(0);
String resultString = searchHit.getSourceAsString();
return resultString;
我只需要在结果中包含两个字段recipe_ID和recipe_url。
您走在正确的道路上,尽管源过滤要求您在如下所示的数组中指定字段:
String[] includeFields = new String[] {"recipe_ID", "recipe_url"};
sourceBuilder.fetchSource(includeFields, null);