ElasticSearch 实战:查询Sort(查询排序)
在ElasticSearch中,我们可以使用sort参数来对查询结果进行排序。
以下是一些使用ElasticSearch的Java API进行查询排序的示例。
- 使用单个字段排序
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort("field_name", SortOrder.ASC);
searchRequest.source(searchSourceBuilder);
try {
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
for (SearchHit hit : searchHits) {
System.out.println(hit.getSourceAsString());
}
} catch (IOException e) {
e.printStackTrace();
}
在这个例子中,我们对"index\_name"索引的所有文档进行查询,并按照"field\_name"字段升序排序。
- 使用多个字段排序
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort("field_name1", SortOrder.ASC);
searchSourceBuilder.sort("field_name2", SortOrder.DESC);
searchRequest.source(searchSourceBuilder);
try {
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
for (SearchHit hit : searchHits) {
System.out.println(hit.getSourceAsString());
}
} catch (IOException e) {
e.printStackTrace();
}
在这个例子中,我们对"index\_name"索引的所有文档进行查询,并先按照"field\_name1"字段升序排序,若"field\_name1"字段值相同,则按照"field\_name2"字段降序排序。
- 使用脚本字段排序
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort(new ScriptSortBuilder(
new Script(ScriptType.INLINE, "painless", "_value * doc['field_name'].value", Collections.emptyMap()),
SortOrder.ASC)
);
searchRequest.source(searchSourceBuilder);
try {
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
for (SearchHit hit : searc
评论已关闭