java(springboot)对接elasticsearch8+

这篇具有很好参考价值的文章主要介绍了java(springboot)对接elasticsearch8+。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、pom引用

注:jackson包es只用到了databind,之所以全部引用是因为actuator用到了其他,只升级一个会 导致版本冲突

<!-- https://mvnrepository.com/artifact/co.elastic.clients/elasticsearch-java -->
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
    <groupId>jakarta.json</groupId>
    <artifactId>jakarta.json-api</artifactId>
    <version>2.1.2</version>
</dependency>

2、配置文件

注:因为没有用springboot自身的es插件所以健康检查检测不到es状态,关闭es检测

elasticsearch:
  host: 10.247.149.67
  port: 9200
  userName: elastic
  password: Zlens@2023
management:
  health:
    elasticsearch:
      enabled: false

3、连接池

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.alibaba.cloud.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.host}")
    private String host;
    @Value("${elasticsearch.port}")
    private Integer port;
    @Value("${elasticsearch.apiKey:}")
    private String apiKey;
    @Value("${elasticsearch.userName}")
    private String userName;
    @Value("${elasticsearch.password}")
    private String password;


    @Bean
    public ElasticsearchClient elasticsearchClient() {
        ElasticsearchTransport transport;
        RestClient restClient;
        if(StringUtils.isNotBlank(apiKey)){
            //apiKey验证模式
            restClient = RestClient
                    .builder(new HttpHost(host, port))
                    .setDefaultHeaders(new Header[]{
                            new BasicHeader("Authorization", "ApiKey " + apiKey)})
                    .build();

        }else{
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            // 账号密码验证模式
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            restClient = RestClient.builder(new HttpHost(host, port))
                    .setHttpClientConfigCallback(httpClientBuilder ->
                            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
        }
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        System.out.println("es初始化完成");
        return client;
    }
}

4、操作类

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.DateProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

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

@Service
@Log4j2
public class ElasticsearchService<T> {
    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * 判断索引是否存在.
     *
     * @param indexName index名称
     */
    public boolean existIndex(String indexName) {
        try {
            BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));
            return booleanResponse.value();
        } catch (IOException e) {
            log.error("向es中检测索引【{}】出错,错误信息为:{}", indexName, e.getMessage());
            throw new RuntimeException("向es中检测索引【"+indexName+"】出错");
        }
    }

    /**
     * 创建索引.
     *
     * @param indexName index名称
     */
    public void createIndex(String indexName) {
        try {
            Map<String, Property> documentMap = new HashMap<>();
            documentMap.put("createTime", Property.of(property ->
                            property.date(DateProperty.of(dateProperty ->
                                            dateProperty.index(true).format("epoch_millis"))
                                    //textProperty.index(true))
                            )
                    )
            );
            elasticsearchClient.indices().create(c -> c.index(indexName).mappings(mappings ->
                    mappings.properties(documentMap)));
        } catch (IOException e) {
            log.error("向es中创建索引【{}】出错,错误信息为:{}", indexName, e.getMessage());
        }
    }

    /**
     * 添加记录.
     *
     */
    public void addDocument(T data, String indexName) {
        try {
            if (!this.existIndex(indexName)) {
                this.createIndex(indexName);
            }
            elasticsearchClient.index(i -> i.index(indexName).id(null).document(data));
        } catch (IOException e) {
            log.error("向es中添加document出错:{}", e.getMessage());
        }
    }

    /**
     * 批量添加.
     *
     * @param dataList 添加的数量集合
     * @param indexName indexName
     */
    public void batchAddDocument(List<T> dataList, String indexName) {
        if (!this.existIndex(indexName)) {
            this.createIndex(indexName);
        }

        BulkRequest.Builder br = new BulkRequest.Builder();
        dataList.forEach(data -> br.operations(op -> op
                .index(idx -> idx
                        .index(indexName)
                        .id(null)
                        .document(data)
                ))
        );

        try {
            BulkResponse result = elasticsearchClient.bulk(br.build());
            if (result.errors()) {
                log.error("Bulk had errors");
                for (BulkResponseItem item : result.items()) {
                    if (item.error() != null) {
                        log.error(item.error().reason());
                    }
                }
            }
        } catch (IOException e) {
            log.error("向es中添加document出错:{}",e.getMessage());
        }
    }

    /**
     * 根据索引名称和字段查询数据.
     *
     * @param indexName 索引名称
     * @param filedValue 查询字段值
     * @param filedName 查询字段名称
     */
    public List<T> findDataList(String indexName, String filedName, String filedValue,Class<T> className) {
        try {
            SearchResponse<T> searchResponse = elasticsearchClient.search(s -> s.index(indexName)
                            .query(q -> q
                                    .match(t -> t
                                            .field(filedName)
                                            .query(filedValue)
                                    )),
                    className);
            List<Hit<T>> hitList = searchResponse.hits().hits();
            List<T> dataList = new ArrayList<>();
            for (Hit<T> mapHit : hitList) {
                dataList.add(mapHit.source());
            }
            return dataList;
        } catch (IOException e) {
            log.error("【查询 -> 失败】从es中查询分析后的日志出错,错误信息为:{}", e.getMessage());
        }
        return null;
    }
}

上边创建索引是定制的加了特殊mapping,正常这样文章来源地址https://www.toymoban.com/news/detail-602596.html


    /**
     * 创建索引.
     *
     * @param indexName index名称
     */
    public void createIndex(String indexName) {
        try {
            elasticsearchClient.indices().create(c -> c.index(indexName));
        } catch (IOException e) {
            log.error("向es中创建索引【{}】出错,错误信息为:{}", indexName, e.getMessage());
        }
    }

到了这里,关于java(springboot)对接elasticsearch8+的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot集成Elasticsearch8.x(7)|(新版本Java API Client使用完整示例)

    章节 第一章链接: SpringBoot集成Elasticsearch7.x(1)|(增删改查功能实现) 第二章链接: SpringBoot集成Elasticsearch7.x(2)|(复杂查询) 第三章链接: SpringBoot集成Elasticsearch7.x(3)|(aggregations之指标聚合查询) 第四章链接: SpringBoot集成Elasticsearch7.x(4)|(aggregations之分桶聚合查询)

    2024年02月16日
    浏览(48)
  • springboot3整合elasticsearch8.7.0实现为bean对象创建索引添加映射

    目录 准备工作 添加相关依赖 在yml中配置elasticsearch 主要内容 实体类 ElasticSearch配置类 测试 确认当前没有counter索引 启动spring 再次查询counter索引​ 在测试类中输出counter索引的映射 官方文档 要注意版本对应关系 spring官方文档中有版本对照表 目前我使用的都是最新的版本,

    2024年02月03日
    浏览(51)
  • ElasticSearch8 - SpringBoot整合ElasticSearch

    springboot 整合 ES 有两种方案,ES 官方提供的 Elasticsearch Java API Client 和 spring 提供的 [Spring Data Elasticsearch](Spring Data Elasticsearch) 两种方案各有优劣 Spring:高度封装,用着舒服。缺点是更新不及时,有可能无法使用 ES 的新 API ES 官方:更新及时,灵活,缺点是太灵活了,基本是一

    2024年03月25日
    浏览(85)
  • springboot整合elasticsearch8

    1.引入maven依赖 2.application.yml添加配置 3.编写config文件 启动demo项目,通过控制台日志查看是否能够正常连接es。 4.在DemoApplicationTests编写简单测试操作es。

    2024年02月12日
    浏览(39)
  • SpringBoot连接ElasticSearch8.*

    系统中需要使用到ElasticSearch进行内容检索,因此需要搭建SpringBoot + ElasticSearch的环境。

    2024年02月16日
    浏览(35)
  • 【springboot-04】ElasticSearch8.7搜索

    为什么学?因为它 查询速度很快 ,而且是非关系型数据库 (NoSql) 一些增删改查已经配置好了,无需重复敲码 ElasticSearch 更新快,本篇文章将主要介绍一些常用方法。 对于 spirngboot 整合 Es 的文章很少,有些已经过时【更新太快了】  依赖:Maven 配置类:EsConfig 水果信息

    2024年02月07日
    浏览(39)
  • springboot整合elasticsearch8组合条件查询

    整合过程见上一篇文章 springboot整合elasticsearch8 1.es8多条件组合查询 2.使用scroll进行大数据量查询

    2024年02月16日
    浏览(41)
  • springBoot整合ElasticSearch8.x版本

    导入依赖   dependency         groupIdcom.fasterxml.jackson.core/groupId         artifactIdjackson-databind/artifactId         version2.13.2/version   /dependency     dependency         groupIdorg.glassfish/groupId         artifactIdjakarta.json/artifactId         version2.0.1/version   /dependency           dependency  

    2023年04月21日
    浏览(33)
  • java 对接国标摄像头流程、代码整合 springboot SIP -GB2818

    java 对接设备的代码资料较少,这里介绍 GB2818 的基本对接流程,有用自取👇 java负责SIP信令的注册交互,推流、拉流鉴权 摄像头负责推流、流媒体负责拉流、转码 wvp-GB28181-pro项目 ,如果java对接各种摄像头,这个项目很👍,比较完善,可参考。进去 star 支持一波 做到需要播

    2024年02月15日
    浏览(30)
  • Springboot3.1+Elasticsearch8.x匹配查询

    springboot-starter3.1.0中spring-data-elasticsearch的版本为5.1.0,之前很多方法和类都找不到了。这里主要讲讲在5.1.0版本下如何使用spring data对elesticsearch8.x进行匹配查询。 第一步当然是配置依赖 在这里面,spring-boot-starter-data-elasticsearch是3.1.0的,里面的spring-data-elasticsearch是5.1.0的,服务

    2024年02月15日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包