温馨提示×

java怎么实现es分页查询

小亿
224
2023-10-27 23:19:40
栏目: 编程语言

在Java中,可以使用Elasticsearch的Java客户端库来实现ES分页查询。下面是一个简单的示例代码:

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.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

public class ElasticsearchPaginationExample {
    private static final String INDEX_NAME = "your_index_name";
    private static final int PAGE_SIZE = 10;

    public static void main(String[] args) {
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder("localhost:9200"))) {

            int pageNumber = 1;
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 设置分页
            searchSourceBuilder.from((pageNumber - 1) * PAGE_SIZE);
            searchSourceBuilder.size(PAGE_SIZE);

            // 设置排序
            searchSourceBuilder.sort(SortBuilders.fieldSort("your_field_name").order(SortOrder.ASC));

            // 设置查询条件
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());

            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 处理搜索结果
            // searchResponse.getHits().getHits() 返回的是一个 SearchHit[] 数组,包含了查询到的文档
            // 可以根据需要进行处理
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,首先创建了一个RestHighLevelClient对象来连接到Elasticsearch服务器。然后,使用SearchRequest创建一个查询请求,并使用SearchSourceBuilder来设置分页、排序和查询条件。最后,使用client.search()方法执行查询,并处理返回的SearchResponse对象中的结果。

0