具体的Search_after解释,可以看我这篇文章 elasticsearch 深度分页查询 Search_after(图文教程)
一. 代码
public class Test {
public static void main(String[] args) throws IOException {
// 创建客户端
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "chenyunzhi"));
// 跳过ssl验证
SSLFactory sslFactory = SSLFactory.builder()
.withUnsafeTrustMaterial()
.withUnsafeHostnameVerifier()
.build();
RestClientBuilder builder = RestClient.builder(
new HttpHost("192.168.1.47", 9200,"https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setSSLContext(sslFactory.getSslContext())
.setSSLHostnameVerifier(sslFactory.getHostnameVerifier())
.setDefaultCredentialsProvider(credentialsProvider);
}
});
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
// 客户端连接
ElasticsearchClient client = new ElasticsearchClient(transport);
// 创建pit
OpenPointInTimeRequest.Builder build = new OpenPointInTimeRequest.Builder();
OpenPointInTimeRequest.Builder builder1 = build.index("test-000005").keepAlive(new Time.Builder().time("1m").build());
OpenPointInTimeResponse openPointInTimeResponse = client.openPointInTime(builder1.build());
String id = openPointInTimeResponse.id();
// 构造查询条件
SearchRequest.Builder sort = new SearchRequest.Builder().size(5)
.pit(p->p.id(id).keepAlive(k->k.time("1m")))
.sort(s -> s.field(f -> f.field("name.keyword").order(SortOrder.Desc)));
// 获取第一次查询的结果
List<Hit<HashMap>> hits = client.search(sort.build(), HashMap.class).hits().hits();
// 检查 hits 列表是否为空
if (!hits.isEmpty()) {
// 获取最后一个值的sort
List<String> sort1 = hits.get(hits.size() - 1).sort();
// 再次构造查询条件 加上searchAfter
sort = new SearchRequest.Builder().size(5)
.pit(p->p.id(id).keepAlive(k->k.time("1m")))
.searchAfter(sort1)
.sort(s -> s.field(f -> f.field("name.keyword").order(SortOrder.Desc)));
List<Hit<HashMap>> hits1 = client.search(sort.build(), HashMap.class).hits().hits();
System.out.println("-------------------------第一次查询结果-------------------------");
System.out.println(hits);
System.out.println("-------------------------最后一个值的sort-------------------------");
System.out.println(sort1);
System.out.println("-------------------------第二次查询结果-------------------------");
System.out.println(hits1);
}
// 关闭
client.closePointInTime(c->c.id(id));
transport.close();
}
}
二. 测试结果
参考:https://blog.csdn.net/qq_44056652/article/details/126341810