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

您所在的位置:网站首页 查询elasticsearch版本 SpringBoot整合Elasticsearch(最新最全,高效安装到使用)

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

2024-07-13 23:13| 来源: 网络整理| 查看: 265

文章目录 一、安装Elasticsearch相关插件1.选择版本2.安装Elasticsearch3.安装node4.安装grunt5.安装es-head插件6.安装kibana7.安装ik分词器 二、整合SpringBoot和Elasticearch1.pom.xml2.application.yml3.ElasticSearch(实体类)4.ElasticSearchRepository5.ElasticSearchService6.ElasticSearchServiceImpl7.EsTest8.自定义查询方式

一、安装Elasticsearch相关插件 1.选择版本

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

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

org.springframework.boot spring-boot-starter-parent 2.5.15

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

2.安装Elasticsearch

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

下载上面链接的安装包解压到任意目录启动es /bin/elasticsearch.bat查看安装结果,在网页输入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 server, grunt server是启动命令 如果出现报错

在这里插入图片描述

则使用 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中文社区下载地址

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

在这里插入图片描述

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

在这里插入图片描述

如果想使用ip访问kibana,需要修改 kibana-7.12.0-windows-x86_64/config/kibana.yml 7行 改为 server.host: “0.0.0.0” 如果想使用kibana汉化 需要修改 kibana-7.12.0-windows-x86_64/config/kibana.yml 最后一行 i18n.locale: “zh-CN”

7.安装ik分词器

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

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

在这里插入图片描述

测试ik分词器重启elasticsearch重启kibana进入kibana的开发工具中执行命令测试 开发工具执行命令: GET _analyze{ “analyzer”: “ik_max_word”, “text”: “折上折满减”}执行结果如下 在这里插入图片描述 二、整合SpringBoot和Elasticearch 1.pom.xml org.springframework.boot spring-boot-starter-parent 2.5.15 org.elasticsearch elasticsearch 7.12.0 org.springframework.boot spring-boot-starter-data-elasticsearch 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 { /** * 查询内容标题查询 * @param title 标题 * @param content 内容 * @return 返回关键字高亮的结果集 */ @Highlight( fields = {@HighlightField(name = "title"), @HighlightField(name = "content")}, parameters = @HighlightParameters(preTags = {""}, postTags = {""}, numberOfFragments = 0) ) List 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 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 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 byTitleOrContent = elasticSearchService.findByTitleOrContent("xxxxxxSpringData","elasticSearch"); for (SearchHit elasticSearchService : byTitleOrContent) { List title = elasticSearchService.getHighlightField("title"); System.out.println(title); List 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);BeforefindByPriceBeforeAfterfindByPriceAfterLike比较相识的数据findByNameLikeStartingWith以xx开头的 数据findByNameStartingWith(String Name);EndingWith以xx结尾的 数据findByNameEndingWith(String Name);Contains/Containing包含的 数据findByNameContaining(String Name);In多 值匹配findByNameIn(Collectionnames)NotIn多 值 不匹配findByNameNotIn(Collectionnames)OrderBy排序 后的数据findByxxxxxOrderByNameDesc(String xxx );


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3