在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`对象中的结果。