在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
對象中的結果。