文档-高级查询-排序
# SearchRequest
创建 Test14_Doc_Query_Sort
package com.stt.demo;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
public class Test14_Doc_Query_Sort {
public static void main(String[] args) throws IOException {
// 创建客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 创建查询请求对象
SearchRequest request = new SearchRequest();
request.indices("student");
// 构建查询请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
// 排序
builder.sort("age", SortOrder.ASC);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询后匹配
System.out.println("took:" + response.getTook());
System.out.println("time out:" + response.isTimedOut());
SearchHits hits = response.getHits();
System.out.println("total:" + hits.getTotalHits());
System.out.println("max score:" + hits.getMaxScore());
System.out.println("-----hits------");
for (SearchHit hit : hits) {
// 输出每条查询的记录
System.out.println(hit.getSourceAsString());
}
// 关闭客户端
client.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
返回
took:33ms
time out:false
total:5 hits
max score:NaN
-----hits------
{"name":"lisi","nickname":"lisi","sex":"男","age":20}
{"name":"zhangsan","nickname":"zhangsan","sex":"男","age":30}
{"name":"zhangsan2","nickname":"zhangsan2","sex":"女","age":30}
{"name":"wangwu","nickname":"wangwu","sex":"女","age":40}
{"name":"zhangsan1","nickname":"zhangsan1","sex":"女","age":50}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Last Updated: 2022/02/05, 15:58:51