【极光系列】springBoot集成elasticsearch

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 【极光系列】springBoot集成elasticsearch

【极光系列】springBoot集成elasticsearch

一.gitee地址

直接下载解压可用 https://gitee.com/shawsongyue/aurora.git

模块:aurora_elasticsearch

二.windows安装elasticsearch

tips:注意es客户端版本要与java依赖版本一致,目前使用7.6.2版本

elasticsearch 7.6.2版本客户端下载: https://www.elastic.co/cn/downloads/elasticsearch

1.下载对应版本资源包

登录页面–》View path releases–》选择7.6.2版本–》window下载

2.解压缩,启动服务

直接点击E:\elasticsearch-7.6.2\bin\elasticsearch.bat启动

三.springBoot集成elasticsearch步骤

1.引入pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xsy</groupId>
    <artifactId>aurora_elasticsearch</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--基础SpringBoot依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
    </parent>
    <!--属性设置-->
    <properties>
        <!--java_JDK版本-->
        <java.version>1.8</java.version>
        <!--maven打包插件-->
        <maven.plugin.version>3.8.1</maven.plugin.version>
        <!--编译编码UTF-8-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--输出报告编码UTF-8-->
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!--json数据格式处理工具-->
        <fastjson.version>1.2.75</fastjson.version>
        <!--json数据格式处理工具-->
        <xxljob.version>2.3.0</xxljob.version>
        <!--elasticsearch依赖-->
        <elasticsearch.version>7.6.2</elasticsearch.version>
    </properties>
    <!--通用依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!--es    start-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!--es  end-->
    </dependencies>
    <!--编译打包-->
    <build>
        <finalName>${project.name}</finalName>
        <!--资源文件打包-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <!--插件统一管理-->
        <pluginManagement>
            <plugins>
                <!--maven打包插件-->
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>${spring.boot.version}</version>
                    <configuration>
                        <fork>true</fork>
                        <finalName>${project.build.finalName}</finalName>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <!--编译打包插件-->
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.plugin.version}</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                        <encoding>UTF-8</encoding>
                        <compilerArgs>
                            <arg>-parameters</arg>
                        </compilerArgs>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <!--配置Maven项目中需要使用的远程仓库-->
    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <url>https://maven.aliyun.com/nexus/content/groups/public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <!--用来配置maven插件的远程仓库-->
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-plugin</id>
            <url>https://maven.aliyun.com/nexus/content/groups/public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

2.修改application配置

#服务配置
server:
  #端口
  port: 7005
#spring配置
spring:
  #应用配置
  application:
    #应用名
    name: aurora_elasticsearch
  #es配置
elasticsearch:
  host: localhost
  port: 9200
  scheme: http

3.包结构

4.创建主启动类

package com.aurora;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @author 浅夏的猫
 * @description 主启动类
 * @date 22:46 2024/1/13
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

5.创建配置类

package com.aurora.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @description es配置
 * @author 浅夏的猫
 * @datetime 6:14 2024/1/20
*/
@Configuration
public class ElasticsearchConfig {
    @Value("${elasticsearch.host}")
    private String host;
    @Value("${elasticsearch.port}")
    private int port;
    @Value("${elasticsearch.scheme}")
    private String scheme;
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, port, scheme)));
    }
}

6.创建工具类

package com.aurora.utils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class ElasticsearchUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public boolean createIndex(String index) {
        boolean ackFlag = false;
        CreateIndexRequest request = new CreateIndexRequest(index);
        try {
            CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            ackFlag = response.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFlag;
    }
    public boolean indexDocument(String index, String id, String jsonSource) {
        boolean ackFlag = false;
        IndexRequest request = new IndexRequest(index)
                .id(id)
                .source(jsonSource, XContentType.JSON);
        try {
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            ackFlag = response.status() == RestStatus.CREATED || response.status() == RestStatus.OK;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFlag;
    }
    public String getDocument(String index, String id) {
        GetRequest getRequest = new GetRequest(index, id);
        String sourceAsString = null;
        try {
            sourceAsString = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT).getSourceAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourceAsString;
    }
    public boolean updateDocument(String index, String id, String jsonSource) {
        boolean ackFLag = false;
        UpdateRequest request = new UpdateRequest(index, id)
                .doc(jsonSource, XContentType.JSON);
        try {
            UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
            ackFLag = response.status() == RestStatus.CREATED || response.status() == RestStatus.OK;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFLag;
    }
    public boolean deleteDocument(String index, String id) {
        boolean ackFlag = false;
        DeleteRequest request = new DeleteRequest(index, id);
        try {
            DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            ackFlag = response.status() == RestStatus.OK;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFlag;
    }
}

7.创建控制类

package com.aurora.controller;
import com.alibaba.fastjson.JSONObject;
import com.aurora.utils.ElasticsearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @description 资源控制类
 * @author 浅夏的猫
 * @datetime 6:21 2024/1/20
*/
@RestController
@RequestMapping("resource")
public class ElasticsearhController {
    private static Logger logger = LoggerFactory.getLogger(ElasticsearhController.class);
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @RequestMapping("esOperate")
    public String esOperate(){
        String index="aurora-20240120";
        JSONObject esJsonObj = new JSONObject();
        String id="aurora002";
        esJsonObj.put("id",id);
        esJsonObj.put("resourceName","aurora源码下载包");
        esJsonObj.put("resourceUrl","http://baidu.com");
        esJsonObj.put("resourceType","1");
        esJsonObj.put("resourceDescribe","aurora资源下载包,大概10M");
        //插入
        boolean insertFlag = elasticsearchUtil.indexDocument(index, id, esJsonObj.toString());
        logger.info("插入数据是否成功:{}",insertFlag);
        //查询
        String document = elasticsearchUtil.getDocument(index,id);
        logger.info("从es索引查询数据:{}",document);
        //更新
        boolean updateFlag = elasticsearchUtil.updateDocument(index, id, esJsonObj.toString());
        logger.info("更新数据是否成功:{}",updateFlag);
        //删除
        boolean deleteFlag = elasticsearchUtil.deleteDocument(index, id);
        logger.info("删除数据是否成功:{}",deleteFlag);
        //查询
        String documentDelete = elasticsearchUtil.getDocument(index,id);
        logger.info("删除后,查询es索引查询数据:{}",documentDelete);
        return "ok";
    }
}

8.访问地址验证

http://localhost:7005/resource/esOperate

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
18天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
25天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
280 0
|
30天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
424 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
272 1
|
1天前
|
Java Docker 容器
SpringBoot项目集成XXL-job
SpringBoot项目集成XXL-job
|
3天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
18天前
|
SQL Java 调度
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
|
26天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
54 1
|
29天前
|
Java 测试技术 Maven
SpringBoot集成Elasticsearch
SpringBoot集成Elasticsearch
24 0
|
1月前
|
缓存 NoSQL Java
springboot中集成redis,二次封装成工具类
springboot中集成redis,二次封装成工具类
174 0