1. 程式人生 > 實用技巧 >Elasticsearch7.4 spring boot 使用 RestHighLevelClient實現searchAfter分頁

Elasticsearch7.4 spring boot 使用 RestHighLevelClient實現searchAfter分頁

官網searchafter介紹:https://www.elastic.co/guide/en/elasticsearch/reference/7.x/paginate-search-results.html#search-after

官網介紹的查詢返回如下:

{
  "pit_id" : "46ToAwEPbXktaW5kZXgtMDAwMDAxFnVzaTVuenpUVGQ2TFNheUxVUG5LVVEAFldicVdzOFFtVHZTZDFoWWowTGkwS0EAAAAAAAAAAAQURzZzcUszUUJ5U1NMX3Jyak5ET0wBFnVzaTVuenpUVGQ2TFNheUxVUG5LVVEAAA==", 
  
"took" : 17, "timed_out" : false, "_shards" : ..., "hits" : { "total" : ..., "max_score" : null, "hits" : [ ... { "_index" : "my-index-000001", "_id" : "FaslK3QBySSL_rrj9zM5", "_score" : null, "_source" : ..., "sort" : [ 4098435132000, "FaslK3QBySSL_rrj9zM5"
] } ] } }

其中,sort陣列長度為2.

但在實現測試中發現7.4版本es查詢返回時,長度為一

{
  "took" : 191,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10000,
      "relation" : "gte"
    },
    "max_score" : null
, "hits" : [ { "_index" : "atc_drg_stat", "_type" : "man", "_id" : "1000", "_score" : null, "_source" : { "district_code" : "DistrictCode", --------------- }, "sort" : [ 1000 ]

不知道是否是版本變化引起的。

程式碼如下:

@RequestMapping("/searchAfter")
    public void searchAfter() throws IOException {
        String searchAfter =null;
        Object[] objects = new Object[]{};
        try {
            for (int i = 0; i < 100; i++) {
                SearchRequest searchRequest = new SearchRequest(index);
                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                searchSourceBuilder.query(matchQuery("year_month", "yearMonth"));
                searchSourceBuilder.size(1000);
                searchSourceBuilder.sort("sort_id", SortOrder.ASC);
                if(objects.length>0) {
                    searchSourceBuilder.searchAfter(objects);
                }
                searchRequest.source(searchSourceBuilder);
                System.out.println(searchRequest.source().toString());
                SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
                System.out.println(searchResponse);
                SearchHit[] hits = searchResponse.getHits().getHits();
                objects = hits[hits.length-1].getSortValues();

                System.out.println(hits);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }