我正在使用弹性 RestHighLevelClient 与 ES 对话。我可以查询基本查询。但是,我正在尝试使用
search_after
api 从我的前端查询中设计分页 api。虽然 query_after
在 RestLowLevelClient api 中使用起来很简单,但我无法弄清楚如何在 HighLevel API 中使用它。
看起来Lucene api有SearchAfterSortedDocQuery,但我不知道如何将它与elasticsearch api一起使用。例如:在下面的代码中,我初始化 SearchAfterSortedDocQuery 查询,但不确定如何使用它。
RestHighLevelClient client = ESRestClient.getClient();
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("field1",value1));
searchSourceBuilder.query(QueryBuilders.termQuery("field2",value2));
searchSourceBuilder.from(0);
searchSourceBuilder.size(limit);
SortField[] sortFields = new SortField[2];
sortFields[0]= new SortField("field1", SortField.Type.LONG);
sortFields[1]= new SortField("field2", SortField.Type.LONG);
FieldDoc fieldDoc = new FieldDoc(0,0); //Is this correct? how to initialize field doc?
fieldDoc.fields = new Object[2];
fieldDoc.fields[0] = new Long("-156034");
fieldDoc.fields[1] = new Long("2297416849");
SearchAfterSortedDocQuery query = new SearchAfterSortedDocQuery(new Sort(sortFields), fieldDoc);
searchRequest.source(searchSourceBuilder);
searchRequest.indices("index1");
try {
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
catch(IOException e){
System.out.println(e);
}
}
我认为您不必使用 SearchAfterSortedDocQuery,只需在 searchSourceBuilder 中设置 search_after 如下所示
searchSourceBuilder.searchAfter(new Object[]{sortAfterValue});
之后使用 SearchRequest 和 Rest 客户端来获取响应
SearchRequest searchRequest = new SearchRequest("index");
searchRequest.types("type");
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT)
SearchHits hits = searchResponse.getHits();
最后,您应该通过 getSortValues() 保留点击中的最后一个排序值,以转到下一页。
hits.getAt(lastIndex).getSortValues()
Elasticsearch search_after api
希望这有帮助。