技术标签: spring boot java elasticsearch es
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最新版整合在后面
- 分布式,无需人工搭建集群(solr就需要人为配置,使用Zookeeper作为注册中心)
- Restful风格,一切API都遵循Rest原则,容易上手
- 近实时搜索,数据更新在Elasticsearch中几乎是完全同步的。
Elasticsearch下载地址 https://www.elastic.co/cn/downloads/elasticsearch
我使用的是7.6.2版本,
将安装包上传到:/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是一个基于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
使用不做介绍
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
使用不做介绍
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>
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);
}
高亮原理:
官方文档介绍: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>
最终效果:
文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99
文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效
文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是
文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件
文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件
文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码
文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware
文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停
文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待
文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析
文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code
文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象