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

一、安装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 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中文社区下载地址

  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首页首页链接

在这里插入图片描述

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

在这里插入图片描述

如果想使用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内。

在这里插入图片描述

  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);
Before findByPriceBefore
After findByPriceAfter
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 );

猜你喜欢

转载自blog.csdn.net/whatevery/article/details/132062101