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);
    }

}
相关推荐
深空数字孪生1 小时前
储能调峰新实践:智慧能源平台如何保障风电消纳与电网稳定?
大数据·人工智能·物联网
百胜软件@百胜软件1 小时前
胜券POS:打造智能移动终端,让零售智慧运营触手可及
大数据
摩羯座-185690305942 小时前
Python数据可视化基础:使用Matplotlib绘制图表
大数据·python·信息可视化·matplotlib
雁于飞2 小时前
vscode中使用git、githup的基操
笔记·git·vscode·学习·elasticsearch·gitee·github
在未来等你3 小时前
Kafka面试精讲 Day 13:故障检测与自动恢复
大数据·分布式·面试·kafka·消息队列
jiedaodezhuti3 小时前
Flink通讯超时问题深度解析:Akka AskTimeoutException解决方案
大数据·flink
庄小焱3 小时前
大数据存储域——Kafka实战经验总结
大数据·kafka·大数据存储域
zskj_qcxjqr4 小时前
告别传统繁琐!七彩喜艾灸机器人:一键开启智能养生新时代
大数据·人工智能·科技·机器人
今生相伴9914 小时前
ELFK:企业级日志管理的完整解决方案——从入门到精通
运维·elk·elasticsearch
每日新鲜事5 小时前
Saucony索康尼推出全新 WOOOLLY 运动生活羊毛系列 生动无理由,从专业跑步延展运动生活的每一刻
大数据·人工智能