ElasticSearch工具类 - ESUtils

1、引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.15.0</version>
</dependency>

2、es配置

java 复制代码
spring:
  data:
    elasticsearch:
      cluster-nodes: localhost:9200

3、创建ESUtils工具类

java 复制代码
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class ESUtils {
    @Resource
    private RestHighLevelClient elasticsearchClient;

    /**
     * 滚动查询全部数据
     * @param indexName 查询的索引 - 数据库
     */
    public List<String> queryDataInRange(String indexName, SearchSourceBuilder sourceBuilder) {
        List<String> results = new ArrayList<>();
        String scrollId = null;
        try {
            SearchRequest searchRequest = new SearchRequest(indexName)
                    .source(sourceBuilder)
                    .scroll(TimeValue.timeValueMinutes(1));

            // 执行搜索请求,获取第一批数据和 scrollId
            SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
            scrollId = searchResponse.getScrollId();
            SearchHit[] searchHits = searchResponse.getHits().getHits();

            // 处理第一批数据
            results.addAll(processHits(searchHits));

            // 滚动查询处理后续的数据
            while (searchHits != null && searchHits.length > 0) {
                SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId)
                        .scroll(TimeValue.timeValueMinutes(1));
                // 滚动查询
                searchResponse = elasticsearchClient.scroll(scrollRequest, RequestOptions.DEFAULT);
                scrollId = searchResponse.getScrollId();
                searchHits = searchResponse.getHits().getHits();

                // 处理后续数据
                results.addAll(processHits(searchHits));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 清除 scroll 上下文
            if (scrollId != null) {
                ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
                clearScrollRequest.addScrollId(scrollId);
                try {
                    elasticsearchClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return results;
    }

    // 处理查询到的数据
    private List<String> processHits(SearchHit[] searchHits) {
        List<String> results = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            results.add(hit.getSourceAsString());
        }
        return results;
    }

}

4、测试工具类

java 复制代码
import com.example.es.utils.ESUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class EsDemoApplicationTests {
    @Resource
    private ESUtils esUtils;

    @Test
    void contextLoads() {
        // 构造初始的搜索请求
        RangeQueryBuilder queryBuilder = QueryBuilders
                .rangeQuery("timeField")
                .gte("2024-03-18 00:00:00")
                .lte("2024-03-18 23:59:59");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
                .query(queryBuilder)
                .sort("timeField", SortOrder.ASC)
                .size(1000);
        List<String> resultMap = esUtils.queryDataInRange("index-Bank", sourceBuilder);
        resultMap.forEach(System.out::println);
    }

}
相关推荐
会飞的老朱6 小时前
医药集团数智化转型,智能综合管理平台激活集团管理新效能
大数据·人工智能·oa协同办公
AI_567810 小时前
AWS EC2新手入门:6步带你从零启动实例
大数据·数据库·人工智能·机器学习·aws
CRzkHbaXTmHw11 小时前
探索Flyback反激式开关电源的Matlab Simulink仿真之旅
大数据
七夜zippoe11 小时前
CANN Runtime任务描述序列化与持久化源码深度解码
大数据·运维·服务器·cann
盟接之桥11 小时前
盟接之桥说制造:引流品 × 利润品,全球电商平台高效产品组合策略(供讨论)
大数据·linux·服务器·网络·人工智能·制造
忆~遂愿12 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
忆~遂愿12 小时前
GE 引擎与算子版本控制:确保前向兼容性与图重写策略的稳定性
大数据·开发语言·docker
米羊12112 小时前
已有安全措施确认(上)
大数据·网络
人道领域14 小时前
AI抢人大战:谁在收割你的红包
大数据·人工智能·算法
qq_124987075314 小时前
基于Hadoop的信贷风险评估的数据可视化分析与预测系统的设计与实现(源码+论文+部署+安装)
大数据·人工智能·hadoop·分布式·信息可视化·毕业设计·计算机毕业设计