elasticsearch8 java 分页

779 阅读1分钟

第一种:普通分页。适合小数据量:from,size

public static void search001() throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
    ClientClass clientClass = getClient();
    ElasticsearchClient esClient = clientClass.getElasticsearchClient();

    String searchText = "萝莉1";

    SearchResponse<Map> response = esClient.search(s -> s
                    .index("user")
                    .query(q -> q
                            .match(t -> t
                                    .field("userName")
                                    .query(searchText)
                            )
                    ).from(10)
                    .size(5)
                    .sort(sort->sort.field(f->f.field("age").order(SortOrder.Desc)))
                    .source(source->source.filter(f->f.includes("userName").excludes(""))),
            Map.class
    );

    TotalHits total = response.hits().total();
    boolean isExactResult = total.relation() == TotalHitsRelation.Eq;

    if (isExactResult) {
        log.info("There are " + total.value() + " results");
    } else {
        log.info("There are more than " + total.value() + " results");
    }

    List<Hit<Map>> hits = response.hits().hits();
    for (Hit<Map> hit: hits) {
        Map source = hit.source();
        log.info("Found product " + source);
    }

    clientClass.close();

}

第二种:scroll分页。官方说已经不推荐这种操作。可参考:``` www.shouxicto.com/article/989…

public static void search002Combile(int page,int pageSize) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
    ClientClass clientClass = getClient();
    ElasticsearchClient esClient = clientClass.getElasticsearchClient();



    String searchText = "萝莉1";

    SearchResponse<Map> response = esClient.search(s -> s
                    .index("user")

                    .query(q->q.matchAll(m->m.queryName("萝莉")))
                    //.from(0)
                    .size(pageSize)
                    .scroll(new Time.Builder().time("600S").build())
                    .sort(sort->sort.field(f->f.field("age").order(SortOrder.Desc)))
                    .sort(sort->sort.field(f->f.field("id").order(SortOrder.Desc))),
                    //.source(source->source.filter(f->f.includes("userName").excludes(""))),
            Map.class
    );



    TotalHits total = response.hits().total();
    long totalDataCount = total.value();
    System.err.println("总数量="+totalDataCount);
    //
    long tempPageNo = totalDataCount % pageSize==0l?totalDataCount / pageSize:(totalDataCount / pageSize)+1L;
    System.err.println("一同多少页="+tempPageNo);

    if(page>1) {
        //首页数据已经拿到
        for (int i = 2; i <= page; i++) {

            ScrollRequest reques = ScrollRequest.of(s -> s.scrollId(response.scrollId()).scroll(new Time.Builder().time("600S").build()));
            ScrollResponse<Map> mapScrollResponse = esClient.scroll(reques, Map.class);
            List<Hit<Map>> hits = mapScrollResponse.hits().hits();
            for (Hit<Map> hit : hits) {
                Map source = hit.source();
                log.info("Found product " + source);
            }
        }
    }else {

        boolean isExactResult = total.relation() == TotalHitsRelation.Eq;

        if (isExactResult) {
            log.info("There are " + total.value() + " results");
        } else {
            log.info("There are more than " + total.value() + " results");
        }

        List<Hit<Map>> hits = response.hits().hits();
        for (Hit<Map> hit : hits) {
            Map source = hit.source();
            log.info("Found product " + source);
            System.err.println(hit.sort());
        }

    }
    clientClass.close();

}

第三种:pageAfter。官方推荐。只适合向下分页,一页一页的翻

public static void searchPageAfter(int page,int pageSize,List<String>afterIdList) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
    ClientClass clientClass = getClient();
    ElasticsearchClient esClient = clientClass.getElasticsearchClient();



    String searchText = "萝莉1";

    SearchResponse<Map> response = esClient.search(s -> s
                    .index("user")

                    .query(q->q.matchAll(m->m.queryName("萝莉")))
                    //.from(0)
                    .size(pageSize)
                    //.scroll(new Time.Builder().time("600S").build())
                    .searchAfter(afterIdList)
                    .sort(sort->sort.field(f->f.field("age").order(SortOrder.Desc)))
                    .sort(sort->sort.field(f->f.field("id").order(SortOrder.Desc))),
            //.source(source->source.filter(f->f.includes("userName").excludes(""))),
            Map.class
    );



    TotalHits total = response.hits().total();
    long totalDataCount = total.value();
    System.err.println("总数量="+totalDataCount);
    //
    long tempPageNo = totalDataCount % pageSize==0l?totalDataCount / pageSize:(totalDataCount / pageSize)+1L;
    System.err.println("一同多少页="+tempPageNo);


        boolean isExactResult = total.relation() == TotalHitsRelation.Eq;

        if (isExactResult) {
            log.info("There are " + total.value() + " results");
        } else {
            log.info("There are more than " + total.value() + " results");
        }

        List<Hit<Map>> hits = response.hits().hits();
        for (Hit<Map> hit : hits) {
            Map source = hit.source();
            log.info("Found product " + source);
            System.err.println(hit.sort());
        }

    //}
    clientClass.close();

}