SpringBoot2.3.4整合ElasticSearch7.6.2
Elasticsearch下载地址 https://www.elastic.co/cn/downloads/elasticsearch
kibana下载地址https://www.elastic.co/cn/downloads/kibana
elasticsearch-analysis-ik 下载地址https://github.com/medcl/elasticsearch-analysis-ik/releases
前三小节简单介绍如何安装,ES7最新版整合在后面
Elasticsearch
- 分布式,无需人工搭建集群(solr就需要人为配置,使用Zookeeper作为注册中心)
- Restful风格,一切API都遵循Rest原则,容易上手
- 近实时搜索,数据更新在Elasticsearch中几乎是完全同步的。
Elasticsearch下载地址 https://www.elastic.co/cn/downloads/elasticsearch
我使用的是7.6.2版本,
Linux安装Elasticsearch
将安装包上传到:/home/moon/ 目录
解压缩
tar xvf elasticsearch-7.6.2.tar.gz
目录重命名
mv elasticsearch-7.6.2/ elasticsearch
# 修改权限
chown moon:moon -R elasticsearch
进入config目录
cd elasticsearch/config/
修改elasticsearch.yml
vim elasticsearch.yml
修改数据和日志目录:
path.data: /home/moon/elasticsearch/data # 数据目录位置
path.logs: /home/moon/elasticsearch/logs # 日志目录位置
修改绑定的ip:
network.host: 0.0.0.0 # 绑定到0.0.0.0,允许任何ip来访问
默认只允许本机访问,修改为0.0.0.0后则可以远程访问
目前我们是做的单机安装,如果要做集群,只需要在这个配置文件中添加其它节点信息即可。
elasticsearch.yml的其它可配置信息:
属性名 | 说明 |
---|---|
cluster.name | 配置elasticsearch的集群名称,默认是elasticsearch。建议修改成一个有意义的名称。 |
node.name | 节点名,es会默认随机指定一个名字,建议指定一个有意义的名称,方便管理 |
path.conf | 设置配置文件的存储路径,tar或zip包安装默认在es根目录下的config文件夹,rpm安装默认在/etc/ elasticsearch |
path.data | 设置索引数据的存储路径,默认是es根目录下的data文件夹,可以设置多个存储路径,用逗号隔开 |
path.logs | 设置日志文件的存储路径,默认是es根目录下的logs文件夹 |
path.plugins | 设置插件的存放路径,默认是es根目录下的plugins文件夹 |
bootstrap.memory_lock | 设置为true可以锁住ES使用的内存,避免内存进行swap |
network.host | 设置bind_host和publish_host,设置为0.0.0.0允许外网访问 |
http.port | 设置对外服务的http端口,默认为9200。 |
transport.tcp.port | 集群结点之间通信端口 |
discovery.zen.ping.timeout | 设置ES自动发现节点连接超时的时间,默认为3秒,如果网络延迟高可设置大些 |
discovery.zen.minimum_master_nodes | 主结点数量的最少值 ,此值的公式为:(master_eligible_nodes / 2) + 1 ,比如:有3个符合要求的主结点,那么这里要设置为2 |
进入Elasticsearch的根目录,然后创建:
mkdir data
mkdir logs
运行
进入elasticsearch/bin目录,可以看到下面的执行文件:
然后输入命令:
./elasticsearch
报错1
[1]: max file descriptors [4096] for elasticsearch process likely too low, increase to at least [65536]
我们用的是moon用户,而不是root,所以文件权限不足。
首先用root用户登录。
然后修改配置文件:
vim /etc/security/limits.conf
添加下面的内容:
* soft nofile 65536
* hard nofile 131072
* soft nproc 4096
* hard nproc 4096
报错2
[2]: max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]
继续修改配置文件:
vim /etc/sysctl.conf
添加下面内容:
vm.max_map_count=655360
然后执行命令:
sysctl -p
报错3
ERROR: [1] bootstrap checks failed
[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
使用用户角色moon,进入elasticsearch.yml
cd elasticsearch/config/
vim elasticsearch.yml
修改配置
cluster.initial_master_nodes: ["node-1"]
重启终端窗口、启动
所有错误修改完毕,一定要重启你的 Xshell终端,否则配置无效
再次启动,终于成功了!
我们在浏览器中访问:http://192.168.5.129:9200
使用不做介绍
Kibana
Kibana是一个基于Node.js的Elasticsearch索引库数据统计工具,可以利用Elasticsearch的聚合功能,生成各种图表,如柱形图,线状图,饼图等。
而且还提供了操作Elasticsearch索引数据的控制台,并且提供了一定的API提示
kibana下载地址https://www.elastic.co/cn/downloads/kibana
我同样下载7.6.2版本
安装
因为Kibana依赖于node,需要在windows下先安装Node.js
安装过程不介绍
在黑窗口输入:
node -v
可以查看到node版本,如下:
然后安装kibana,与elasticsearch保持一致
解压即可:
配置运行
配置
进入安装目录下的config目录,修改kibana.yml文件:
修改elasticsearch服务器的地址:
elasticsearch.hosts: ["http://192.168.5.129:9200"]
运行
进入安装目录下的bin目录:
双击运行:
kibana的监听端口是5601
我们访问:http://127.0.0.1:5601
使用不做介绍
ik分词器
elasticsearch-analysis-ik 下载地址https://github.com/medcl/elasticsearch-analysis-ik/releases
同样7.6.2版本
安装
上传下载的tar包,解压到Elasticsearch目录的plugins目录中:
tar xvf elasticsearch-analysis-ik-7.6.2.tar.gz
得到一个名为elasticsearch的目录:
改名为ik-analyzer
mv elasticsearch ik-analyzer
chown moon:moon ik-analyzer/ -R
然后重启elasticsearch
使用不做介绍
SpringDataElasticsearch
搭建SpringBoot工程并添加依赖
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-data-elastic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elastic</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SpringDataElasticsearch的启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置
spring:
elasticsearch:
rest:
uris: http://192.168.5.129:9200 #ip是我的虚拟机地址
创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "shop",replicas = 0)
public class Book {
@Id
private long id;
@Field(type = FieldType.Integer , index = false)
private int count;
@Field(type = FieldType.Keyword )
private String author;
@Field(type = FieldType.Text , analyzer = "ik_max_word")
private String descr;
@Field(type = FieldType.Text , analyzer = "ik_max_word")
private String name;
@Field(type = FieldType.Date ,format = DateFormat.basic_date_time)
private Instant onSale;
}
几个用到的注解:
- @Document:声明索引库配置
- indexName:索引库名称
- type:
映射类型。如果未设置,则使用小写的类的简单名称。(从版本4.0开始不推荐使用)- shards:分片数量,默认5
- replicas:副本数量,默认1
- @Id:声明实体类的id
- @Field:声明字段属性
- type:字段的数据类型
- analyzer:指定分词器类型
- index:是否创建索引
执行测试
@RestController
@Slf4j
public class ElasticController {
@Autowired
private ElasticsearchRestTemplate esTemplate;
@GetMapping("/create")
public String contextLoads() {
IndexOperations indexOperations = esTemplate.indexOps(Book.class);
Document document = indexOperations.createMapping();
return indexOperations.putMapping(document)?"成功":"失败";
}
}
查看索引库
索引数据操作
SDE的索引数据CRUD并没有封装在ElasticsearchTemplate中,而是有一个叫做ElasticsearchRepository的接口:
我们自定义接口,继承ElasticsearchRespository:
package com.example.springdataelastic.repository;
import com.example.springdataelastic.pojo.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ShopRepository extends ElasticsearchRepository<Book,Long> {
}
创建索引数据
单个创建
//一定要使用自定义的Repository接口
@Autowired
private ShopRepository repository;
@GetMapping("/add")
public void addDocument() throws ParseException {
repository.save(new Book(1L,99999,"余华","生亦何欢,死亦何苦","活着", Instant.now()));
}
通过kibana工具查看数据
批量创建
@GetMapping("/addAll")
public void addAllDocument() throws ParseException {
List<Book> list = new ArrayList<>();
list.add(new Book(6L,99999,"无名","合理组织数据,高效处理数据","数据结构"));
list.add(new Book(2L,99000,"aa","aaDesc","aaName", Instant.now()));
list.add(new Book(3L,963399,"bb","bbDesc","bbName", Instant.now()));
list.add(new Book(4L,19999,"cc","ccDesc","ccName", Instant.now()));
list.add(new Book(5L,991000,"dd","ddDesc","ddName", Instant.now()));
repository.saveAll(list);
}
自定义查询
语法查看官方文档 [8.2. Query methods] 介绍,非常全面
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/
public interface ShopRepository extends ElasticsearchRepository<Book,Long> {
/**
* 根据id范围查询
* @param min 最小值
* @param max 最大值
* @param page 分页信息
* @return 查询集合
*/
Page<Book> findByIdBetween(int min, int max, Pageable page);
}
@GetMapping("/demo1/{page}")
public Page<Book> queryDemo1(@PathVariable("page") int page){
/*
* PageRequest.of(page, size);
* page 当前页码 从0开始
* size 每页个数
*/
Pageable pageable = PageRequest.of(page, 3);
return repository.findByIdBetween(1,5,pageable);
}
自定义高亮结果
高亮原理:
- 服务端搜索数据,得到搜索结果
- 把搜索结果中,搜索关键字都加上约定好的标签
- 前端页面提前写好标签的CSS样式,即可高亮
官方文档介绍:8.4. Annotations for repository methods
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.repositories
从Spring-Data-Elasticsearch4.0开始,支持使用@Highlight注解
public interface ShopRepository extends ElasticsearchRepository<Book,Long> {
//.....
/**
* 根据书名 或 描述查询
* @param name 书名
* @param desc 描述
* @return
*/
@Highlight(fields={
@HighlightField(name="name"),
@HighlightField(name="descr")
})
List<SearchHit<Book>> findByNameOrDescr(String name, String desc);
}
@HighlightField(name="***")
要应用突出显示的字段的名称。该名称必须是实体属性的字段名称,而不是索引映射中字段的名称
@GetMapping("/demo2/{name}/{desc}")
public
List<SearchHit<Book>> queryDemo2(@PathVariable("name") String name,
@PathVariable("desc") String desc){
log.info("执行方法:findByNameOrDescr(name,desc);param[0]="+name+";param[1]="+desc);
return repository.findByNameOrDescr(name,desc);
}
在搜索结果中,突出显示的数据可以从SearchHit
类中检索。
自定义高亮遇到的问题:
在SpringBoot+MybatisPlus+ES+thymeleaf的一个快速上手项目测试中,发现包在高亮字段外面的标签
<em></em>
在浏览器中被转义了,导致高亮效果无法达到预期效果。
原因:
在thymeleaf模板中使用了 th:text,输出时候会把特殊字符转义,导致直接输出标签文本
<a th:if="${not #maps.isEmpty(item.highlightFields)}"
th:text="${item.highlightFields.name.get(0)}"></a>
<a th:unless="${not #maps.isEmpty(item.highlightFields)}"
th:text="${item.content.name}"></a>
解决办法:
把th:text改成th:utext
<a th:if="${not #maps.isEmpty(item.highlightFields)}"
th:utext="${item.highlightFields.name.get(0)}"></a>
<a th:unless="${not #maps.isEmpty(item.highlightFields)}"
th:utext="${item.content.name}"></a>
最终效果: