ElasticSearch 与java的结合使用(一)

引入依赖

java 复制代码
       <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.15.2</version>
            <exclusions>
                <!-- 排除自带的logback依赖 -->
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-core</artifactId>
                </exclusion>

            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.15.2</version>
            <exclusions>
                <!-- 排除自带的logback依赖 -->
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

编写配置类(可配置多数据源)

java 复制代码
#Es地址
es.hostName=localhost
#Es端口号
es.transport=9200
#配置es的集群名称,默认是elasticsearch,es会自动发现在同一网段下的es,如果在同一网段下有多个集群,就可以用这个属性来区分不同的集群
es.cluster.name=elasticsearch_content_aware
#es 访问协议
es.protocol=http
#连接超时时间
es.connectTimeOut = 1000
#socket连接超时时间
es.socketTimeOut = 30000
#获取连接超时时间
es.connectionRequestTimeOut = 500
#最大连接数
es.maxConnectNum = 100
#最大路由连接数
es.maxConnectPerRoute = 100

package com.pys.config;


import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfiguration {
    //集群地址,多个使用','隔开
    @Value("${es.hostName}")
    private String host;
    //端口号
    @Value("${es.transport}")
    private int port;
    //使用的协议
    @Value("${es.protocol}")
    private String schema;
    // private static ArrayList<HttpHost> hostList = null;
    //连接超时时间
    @Value("${es.connectTimeOut}")
    private int connectTimeOut;
    //socket连接超时时间
    @Value("${es.socketTimeOut}")
    private int socketTimeOut;
    //获取连接超时时间
    @Value("${es.connectionRequestTimeOut}")
    private int connectionRequestTimeOut;

    //最大连接数
    @Value("${es.maxConnectNum}")
    private int maxConnectNum;
    //最大路由连接数
    @Value("${es.maxConnectPerRoute}")
    private int maxConnectPerRoute;

    @Bean
    public RestHighLevelClient clien() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, schema));
        //异步httpclient连接延时配置
        builder.setRequestConfigCallback((requestConfigBuilder) -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });
        //异步httpClient连接数配置
        builder.setHttpClientConfigCallback((httpClientBuidler) -> {
            httpClientBuidler.setMaxConnTotal(maxConnectNum);
            httpClientBuidler.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuidler;
        });
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}

基础查询

java 复制代码
数据新增
    public boolean add(String indexName, String id, Object object) {
        IndexRequest indexRequest = new IndexRequest(indexName, "_doc", id);
        indexRequest.source(JSONObject.toJSONString(object), XContentType.JSON);
        try {
            IndexResponse indexResponse = restHighLevelClient
                    .index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("indexResponse:{}"+JSONObject.toJSONString(indexResponse));
            return StringUtils.equalsIgnoreCase("created", indexResponse.getResult().toString());
        } catch (IOException e) {
            System.out.println("添加es数据失败 indexName:{},e:{}"+indexName +"  "+ e);
        }
        return false;
    }
   
  数据删除
      public boolean delete(String indexName, String id) {
        DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
        try {
            DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            return StringUtils.equalsIgnoreCase("deleted", response.getResult().toString());
        } catch (IOException e) {
            log.error("根据ID删除es数据失败 indexName:{},e:{}", indexName, e);
        }
        return false;
    }
数据查询
    public GetResponse get(String indexName, String id) {
        GetRequest getRequest = new GetRequest(indexName, id);
        try {
            GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            return response;
        } catch (IOException e) {
            log.error("根据ID获取es数据失败 indexName:{},e:{}", indexName, e);
        }
        return null;
    }
数据更新
    public boolean update(String indexName, Object object, String id) {
        UpdateRequest updateRequest = new UpdateRequest(indexName, id);
        updateRequest.doc(JSONObject.toJSONString(object), XContentType.JSON);
        try {
            UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            return StringUtils.equalsIgnoreCase("updated", response.getResult().toString());
        } catch (IOException e) {
            log.error("根据Id更新es数据失败 indexName:{},e:{}", indexName, e);
        }
        return false;
    }
相关推荐
历程里程碑2 小时前
MySQL数据类型全解析 + 代码实操讲解
大数据·开发语言·数据库·sql·mysql·elasticsearch·搜索引擎
绘梨衣5472 小时前
django-elasticsearch-dsl-drf 搜索服务搭建教学文档
python·elasticsearch·django
Adolf_19932 小时前
Mac 配置Homebrew + Oh My Zsh + npm全局权限问题
大数据·elasticsearch·搜索引擎
二哈赛车手18 小时前
新人笔记---ES和kibana启动问题以及一些常用的linux的错误排查方法,以及ES,数据库泄密解决方案[超详细]
java·linux·数据库·spring boot·笔记·elasticsearch
摇滚侠1 天前
数据同步 黑马 Elasticsearch 全套教程,黑马旅游网案例
大数据·elasticsearch·搜索引擎
南棱笑笑生1 天前
20260503给万象奥科的开发板HD-RK3576-PI适配瑞芯微原厂的Android14时适配AP6256
大数据·elasticsearch·搜索引擎·rockchip
逸Y 仙X1 天前
文章二十:Elasticsearch高亮搜索完全指南
java·大数据·运维·elasticsearch·搜索引擎·全文检索
Elastic 中国社区官方博客2 天前
ES|QL METRICS_INFO 和 TS_INFO:为你的时间序列数据建立目录
大数据·数据库·elasticsearch·搜索引擎·信息可视化·全文检索
Elastic 中国社区官方博客2 天前
Elastic 和 Cursor 合作 加速 上下文工程 与 coding agents
大数据·人工智能·elasticsearch·搜索引擎·全文检索
二哈赛车手2 天前
新人笔记---实现简易版的rag的bm25检索(利用ES),以及RAG上传时的ES与向量数据库双写
java·数据库·笔记·spring·elasticsearch·ai