SpringBoot整合Elasticsearch(最新最全,高效安装到使用)

news2024/7/6 19:13:29

文章目录

  • 一、安装Elasticsearch相关插件
    • 1.选择版本
    • 2.安装Elasticsearch
    • 3.安装node
    • 4.安装grunt
    • 5.安装es-head插件
    • 6.安装kibana
    • 7.安装ik分词器
  • 二、整合SpringBoot和Elasticearch
    • 1.pom.xml
    • 2.application.yml
    • 3.ElasticSearch(实体类)
    • 4.ElasticSearchRepository
    • 5.ElasticSearchService
    • 6.ElasticSearchServiceImpl
    • 7.EsTest
    • 8.自定义查询方式

一、安装Elasticsearch相关插件

1.选择版本

为了避免使用的Elasticsearch版本和SpringBoot采用的版本不一致导致的问题,尽量使用一致的版本。下表是对应关系:

在这里插入图片描述
我的SpringBoot版本:

<parent>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.15</version>
    <relativePath />
</parent>

所以选择对应Elasticsearch版本为7.12.0。

2.安装Elasticsearch

Elasticsearch各版本下载
Elasticsearch7.12.0官网下载

  1. 下载上面链接的安装包
  2. 解压到任意目录
  3. 启动es /bin/elasticsearch.bat
  4. 查看安装结果,在网页输入localhost:9200,出现下图即为成功

在这里插入图片描述

这时可能会存在一个问题,用localhost可以访问到,用ip访问不到
需要修改Elasticsearch安装目录下的/config/elasticsearch.yml,在58行添加如下设置

network.bind_host: 0.0.0.0

添加完成后,重新启动es服务,可能会出现闪退问题
其中如果问题为:bootstrap check failure [1] of [1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured
需要把Elasticsearch安装目录下的/config/elasticsearch.yml中大概77行位置的

#cluster.initial_master_nodes: ["node-1", "node-2"]

注释放开,改为

cluster.initial_master_nodes: ["node-1"]

3.安装node

es5以上就需要安装node和grunt,所以安装head插件的前提,是需要把该两项配置好。

node下载地址下载对应环境的node版本安装即可。

安装过程结束后,在dos窗口查看是否安装成功,使用命令:node -v,出现如下截图,则说明安装成功。

在这里插入图片描述

4.安装grunt

在node安装路径下,使用命令安装:npm install -g grunt-cli 安装grunt。 安装结束后,使用命令grunt
-version查看是否安装成功,出现如下截图,说明安装成功。

在这里插入图片描述

5.安装es-head插件

方便查看ES中的索引及数据

es-head下载地址

解压elasticsearch-head-master
再改目录下进入cmd命令,执行npm install

在这里插入图片描述

执行完成后运行命令 grunt serve
grunt serve是启动命令
如果出现报错

在这里插入图片描述

则使用 cmd继续执行npm install grunt --save-dev。 这将向package.json添加最新版本。

在这里插入图片描述

如果不报错,则命令窗显示

在这里插入图片描述

浏览器输入127.0.0.1:9100

在这里插入图片描述

这里其实无法连接到elasticsearch, 还需要解决跨域问题
由于前后端分离开发,所以会存在跨域问题,需要在服务端做CORS的配置。
修改Elasticsearch安装目录下的/config/elasticsearch.yml,添加如下设置

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-credentials: true
http.cors.allow-headers: Content-Type,Accept,Authorization,x-requested-with
#http.cors.allow-headers: "*"

重启ES服务

在这里插入图片描述

6.安装kibana

用途:便于通过rest api调试ES。

kibana官方7.12.0下载地址
kibana中文社区下载地址

  1. 解压
  2. 修改 kibana-7.12.0-windows-x86_64/config/kibana.yml 32行
  3. 改为elasticsearch.hosts: [“http://127.0.0.1:9200”]
  4. 保存之后,运行bin/kibana.bat
  5. 浏览器中访问kibana首页首页链接

在这里插入图片描述

直接访问开发工具:开发工具

在这里插入图片描述

7.安装ik分词器

注意:下载的ik分词器版本号要和安装的elasticsearch版本一致

把下载的ik分词器解压至Elasticsearch的安装目录/plugins/ik内。

在这里插入图片描述

  1. 测试ik分词器
  2. 重启elasticsearch
  3. 重启kibana
  4. 进入kibana的开发工具中执行命令测试 开发工具
  5. 执行命令: GET _analyze{ “analyzer”: “ik_max_word”, “text”: “折上折满减”}
  6. 执行结果如下
    在这里插入图片描述

二、整合SpringBoot和Elasticearch

1.pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.15</version>
    <relativePath />
</parent>
<!--springBoot2.5.15对应Elasticsearch7.12.0版本-->
<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.12.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.application.yml

spring:
	elasticsearch:
       rest:
            uris: 192.168.1.36:9200
            connection-timeout: 1s
            read-timeout: 30s

3.ElasticSearch(实体类)

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

//@Document 文档对象 (索引信息、文档类型 )
@Document(indexName="blog3")
@Data
public class ElasticSearch {

    //@Id 文档主键 唯一标识
    @Id
    //@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )
    @Field(store=true, index = false,type = FieldType.Integer)
    private Integer id;

    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String title;

    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String content;

    @Field(index=true,store=true,type = FieldType.Double)
    private Double price;
}

4.ElasticSearchRepository

import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface ElasticSearchRepository extends ElasticsearchRepository<ElasticSearch, Integer> {

    /**
     * 查询内容标题查询
     * @param title 标题
     * @param content 内容
     * @return 返回关键字高亮的结果集
     */
    @Highlight(
            fields = {@HighlightField(name = "title"), @HighlightField(name = "content")},
            parameters = @HighlightParameters(preTags = {"<span style='color:red'>"}, postTags = {"</span>"}, numberOfFragments = 0)
    )
    List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);

}

5.ElasticSearchService

import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.core.SearchHit;
import java.util.List;

public interface ElasticSearchService {

    //保存和修改
    void save(ElasticSearch article);
    //查询id
    ElasticSearch findById(Integer id);
    //删除指定ID数据
    void   deleteById(Integer id);

    long count();
    
    boolean existsById(Integer id);

    List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);

}

6.ElasticSearchServiceImpl

import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import com.economics.project.es.service.ElasticSearchRepository;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Resource
    private ElasticSearchRepository ElasticSearchRepository;


    @Override
    public void save(ElasticSearch ElasticSearch) {
        ElasticSearchRepository.save(ElasticSearch);
    }

    @Override
    public ElasticSearch findById(Integer id) {
        return ElasticSearchRepository.findById(id).orElse(new ElasticSearch());
    }

    @Override
    public void deleteById(Integer id) {
        ElasticSearchRepository.deleteById(id);
    }

    @Override
    public long count() {
        return ElasticSearchRepository.count();
    }

    @Override
    public boolean existsById(Integer id) {
        return ElasticSearchRepository.existsById(id);
    }

    @Override
    public List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content) {
        return ElasticSearchRepository.findByTitleOrContent(title,content);
    }

}

7.EsTest

import com.economics.EconomicsApplication;
import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EconomicsApplication.class)
public class EsTest {

    @Resource
    private ElasticSearchService elasticSearchService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**创建索引和映射*/
    @Test
    public void createIndex(){

//        elasticsearchTemplate.createIndex(ElasticSearch.class);
//        elasticsearchTemplate.putMapping(ElasticSearch.class);
    }

    /**添加文档或者修改文档(以id为准)*/
    @Test
    public void saveElasticSearch(){
        ElasticSearch elasticSearch = new ElasticSearch();
        elasticSearch.setId(1);
        elasticSearch.setTitle("SpringData ElasticSearch");
        elasticSearch.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
                "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        elasticSearchService.save(elasticSearch);
    }
    @Test
    public void findById(){
        ElasticSearch byId = elasticSearchService.findById(1);
        System.out.println(byId);
    }
    @Test
    public void deleteById(){
        elasticSearchService.deleteById(100);

    }
    @Test
    public void count(){
        long count = elasticSearchService.count();
        System.out.println(count);
    }
    @Test
    public void existsById(){
        boolean b = elasticSearchService.existsById(102);

        System.out.println(b);
    }
    @Test
    public void findByTitleOrContent(){
        List<SearchHit<ElasticSearch>> byTitleOrContent = elasticSearchService.findByTitleOrContent("xxxxxxSpringData","elasticSearch");
        for (SearchHit<ElasticSearch> elasticSearchService : byTitleOrContent) {
            List<String> title = elasticSearchService.getHighlightField("title");
            System.out.println(title);
            List<String> content = elasticSearchService.getHighlightField("content");
            System.out.println(content);

        }
    }
}

8.自定义查询方式

关键字解释方法
and根据Field1和Field2获得数据findByTitleAndContent(String title,String content);
or根据Field1或Field2获得数据findByTitleOrContent(String title,String content);
is根据Field获得数据findByTitle(String title);
not根据Field获得相反数据findByTitleNot(String title)
between获得指定范围的数据findByPriceBetween(double price1, double price2);
lessThanEqual获得小于等于指定值的数据findByPriceLessThan(double price);
GreaterThanEqual获得大于等于指定值的数据findByPriceGreaterThan(double price);
BeforefindByPriceBefore
AfterfindByPriceAfter
Like比较相识的数据findByNameLike
StartingWith以xx开头的 数据findByNameStartingWith(String Name);
EndingWith以xx结尾的 数据findByNameEndingWith(String Name);
Contains/Containing包含的 数据findByNameContaining(String Name);
In多 值匹配findByNameIn(Collectionnames)
NotIn多 值 不匹配findByNameNotIn(Collectionnames)
OrderBy排序 后的数据findByxxxxxOrderByNameDesc(String xxx );

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/828193.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

devops(前端)

1.前言 前端的打包流程和后端的流程是一样的&#xff0c;只是打包的环境和制作的镜像有所不同&#xff0c;前端需要使用nodejs环境打包&#xff0c;镜像也是使用nginx镜像&#xff0c;因为用的是k8s的pod运行镜像&#xff0c;还需要使用configmap挂载nginx的配置&#xff0c;一…

04|Oracle学习(外键约束)

备注&#xff1a;下文中出现的 add constraints应改为add constraint&#xff0c;不需要加s 1.外键约束介绍 1.1 什么是外键约束&#xff1a; 如果按下面的设计&#xff0c;直接在原表中添加“班级编号”、“班级名称”、“班主任”、“班级描述”这些列名&#xff0c;会出现…

# Windows 环境下载 Android 12源码

前言 Android 官网&#xff08;该方式不适合 Windows 平台&#xff09;&#xff1a;https://source.android.com/source/downloading.html (备注自 2021 年 6 月 22 日起&#xff0c;安卓操作系统不再支持在 Windows 或 MacOS 上进行构建&#xff0c;如果要编译源码推荐先安装…

JavaScript Object所有方法

下面将会一一介绍上面的方法。 Object.create Object.create() 方法创建一个拥有指定原型和若干个指定属性的对象。 Object.create(proto [, propertiesObject ])proto 为新创建对象的原型对象&#xff0c;设置为null可创建没有原型的空对象。propertiesObject 包涵若干个属性…

Kubernetes系列-Ingress

1 Ingress 概述 Kubernetes 对外暴露服务&#xff08;Service&#xff09;主要有两种方式&#xff1a;NodePort&#xff0c;LoadBalance&#xff0c;此外 externalIps 也可以使各类 service 对外提供服务&#xff0c;但是当集群服务很多的时候&#xff0c;NodePort方式最大的缺…

静态资源导入探究

静态资源可以在哪里找呢&#xff1f;我们看看源码 从这个类进去 里面有个静态类 WebMvcAutoConfigurationAdapter 有个配置类&#xff0c;将这个类的对象创建并导入IOC容器里 这个静态类下有个方法 addResourceHandlers(ResourceHandlerRegistry registry)静态资源处理器 若自…

【测试联调】如何在前后端测试联调时优雅的构造异常场景

目录 背景 使用iptables实现 利用iptables丢弃某ip数据包 使用 -L 列出所有规则 IP 连通性 通信 测试 插入一条规则&#xff0c;丢弃此ip 的所有协议请求 列出所有规则 测试 丢弃规则内的IP 连通性 清除 规则列表的 限制 模拟ip进行丢包50%的处理。 mysql proxy 代理…

面试总结-Redis篇章(十一)——分片集群、数据读写规则

分片集群、数据读写规则 主从&#xff08;解决高并发&#xff09;和哨兵&#xff08;解决高可用&#xff09;分别解决了高并发读、高可用的问题。但是依然有两个问题没有解决&#xff1a;解决办法&#xff1a;使用分片集群可以解决上述问题。 特征&#xff1a;客户端请求可以访…

【uni-app】【Android studio】手把手教你运行uniapp项目到Android App

最开始想写一个自定义背景的弹窗&#xff0c;因为要用到项目的好几个地方&#xff0c;不希望每个地方都需要引入。而且只需要放张图片&#xff0c;加个关闭按钮和功能按钮就行&#xff0c;类似这种效果&#xff1a; 开始写的时候找了一篇博客&#xff0c;写的很详细&#xff0…

vue element el-upload附件上传、在线预览、下载当前预览文件

上传 在线预览&#xff08;iframe&#xff09;&#xff1a; payload&#xff1a; response&#xff1a; 全部代码&#xff1a; <template><div><el-table :data"tableData" border style"width: 100%"><el-table-column prop"d…

论文阅读 - Social bot detection in the age of ChatGPT: Challenges and opportunities

论文链接&#xff1a;https://www.researchgate.net/publication/371661341_Social_bot_detection_in_the_age_of_ChatGPT_Challenges_and_opportunities 目录 摘要&#xff1a; 引言 1.1. Background on social bots and their role in society 1.2. The rise of AI-gene…

细扒电驱电控整合趋势

电机和电控的配套量方面&#xff0c;领先都是比亚迪的弗迪动力。这与比亚迪整车销量显著领先分不开。在电机和电控排名靠前的企业中&#xff0c;有很多相同的企业。根据科瑞三电系统数据的统计&#xff0c;72%的电机电控来自同一企业&#xff0c;这部分业务量在2022年的同比增速…

剑指大厂,手撕 Java 八股文

tip: 此贴为目录贴&#xff0c;定期更新 toNew: 时间是最好的答案&#xff0c;它能解决所有问题。坚持&#xff01;&#xff01;&#xff01; ✌本文章旨在总结 Java 的知识生态以及帮助需要学习者和求职者&#xff0c;本人从事应用安全和大数据领域&#xff0c;有8年开发经验&…

mse.backward()作用及原理

作用&#xff1a;自动求导。计算那些有关图中叶子节点的tensors的梯度(这里的叶子节点指的是那些require_gardtrue的叶子节点) 计算叶子节点的梯度&#xff0c;自动附加在每个tensor的成员变量上&#xff0c;之后通过变量.grad&#xff0c;比如w.grad,b.grad 来调用。 另外补…

浅谈React中的ref和useRef

目录 什么是useRef&#xff1f; 使用 ref 访问 DOM 元素 Ref和useRef之间的区别 Ref和useRef的使用案例 善用工具 结论 在各种 JavaScript 库和框架中&#xff0c;React 因其开发人员友好性和支持性而得到认可。 大多数开发人员发现 React 非常舒适且可扩展&#xff0c;…

从0到1开发go-tcp框架【3-读写协程分离、引入消息队列、进入连接管理器、引入连接属性】【基础篇完结】

从0到1开发go-tcp框架【3-读写协程分离、引入消息队列、进入连接管理器、引入连接属性】 1 读写协程分离[v0.7] 添加一个Reader和Writer之间通信的channel添加一个Writer goroutineReader由之前直接发送给客户端改为发送给通信channel启动Reader和Writer一起工作 zinx/znet/co…

TPlink DDNS 内网穿透?外网访问设置方法

有很多小伙伴都想知道&#xff1a;TPlink路由器怎么设置DDNS内网穿透&#xff1f;今天&#xff0c;小编就给大家分享一下TPlink DDNS 外网访问设置方法&#xff0c;下面是图文教程&#xff0c;帮助新手快速入门DDNS设置。 本文介绍的是云路由器TP-LINK DDNS的设置方法。TP-LIN…

【算法提高:动态规划】1.6 区间DP

文章目录 前言例题列表1068. 环形石子合并&#xff08;前缀和 区间DP 环形转换成线性⭐&#xff09;如何把环转换成区间&#xff1f;⭐实现代码补充&#xff1a;相关题目——282. 石子合并 320. 能量项链&#xff08;另一种计算价值的石子合并&#xff09;479. 加分二叉树&am…

企业电子招标采购系统源码Spring Boot + Mybatis + Redis + Layui + 前后端分离 构建企业电子招采平台之立项流程图 tbms

&#xfeff; 项目说明 随着公司的快速发展&#xff0c;企业人员和经营规模不断壮大&#xff0c;公司对内部招采管理的提升提出了更高的要求。在企业里建立一个公平、公开、公正的采购环境&#xff0c;最大限度控制采购成本至关重要。符合国家电子招投标法律法规及相关规范&am…

VBA技术资料MF38:VBA_在Excel中隐藏公式

【分享成果&#xff0c;随喜正能量】佛祖也无能为力的四件事&#xff1a;第一&#xff0c;因果不可改&#xff0c;自因自果&#xff0c;别人是代替不了的&#xff1b;第二&#xff0c;智慧不可赐&#xff0c;任何人要开智慧&#xff0c;离不开自身的磨练&#xff1b;第三&#…