Java elasticsearch-client8.x利用msearch批次查詢

Jackie_JK發表於2024-12-06

示例版本為elasticsearch-java-8.13.4.jar

    LocalDate nowD = now.toLocalDate();
    List<String> indices = ElasticsearchIndex.INDEX.getIndices(nowD.minusDays(interval), nowD);
    List<RequestItem> reqItems = new ArrayList<>(2);

    if (StringUtils.isNotEmpty(AAA)) {
      String finalAAA = AAA;
      Query boolQuery = QueryBuilders.bool(b -> b
          .must(
              QueryBuilders.range(t -> t.field("dateTime").from(now.minusDays(interval).toString()).to(now.toString())),
              QueryBuilders.term(t -> t.field("bbb.keyword").value(bbb)),
          )
      );
      reqItems.add(RequestItem.of(a -> a
          .header(h -> h.index(indices).ignoreUnavailable(true))
          .body(b -> b
              .query(boolQuery)
              .sort(s -> s.field(f -> f.field("dateTime").order(SortOrder.Desc)))
              .size(1)
          )));
    }

    Query boolQuery = QueryBuilders.bool(b -> b
        .must(
            QueryBuilders.range(t -> t.field("dateTime").from(now.minusDays(interval).toString()).to(now.toString())),

        )
    );
    reqItems.add(RequestItem.of(a -> a
        .header(h -> h.index(indices).ignoreUnavailable(true))
        .body(b -> b
            .query(boolQuery)
            .sort(s -> s.field(f -> f.field("dateTime").order(SortOrder.Desc)))
            .size(1)
        )));

    MsearchRequest.Builder builder = new MsearchRequest.Builder();
    builder.searches(reqItems);

    MsearchResponse<AbcRecord> response;
    try {
      response = esClient.msearch(builder.build(), AbcRecord.class);
    } catch (Exception e) {
      return false;
    }
    List<MultiSearchResponseItem<AbcRecord>> responses = response.responses();

相關文章