ElasticSearch 7 入门使用教程
ElasticSearch Linux版安装
安装JDK环境
执行如下命令:
安装JDK并查看JDK版本
$ yum install java-1.8.0-openjdk.x86_64 $ java -version
安装ES7版本程序包
执行如下命令,下载程序包到当前路径下:
$ curl -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.12.0-linux-x86_64.tar.gz
解压压缩包:
$ tar -zxvf elasticsearch-7.12.0-linux-x86_64.tar.gz
安装vim编辑器:
$ yum install -y vim
编辑ElasticSearch配置项
进入elasticsearch程序包(本人将elasticsearch程序包移动至/opt/es/文件夹下)
编辑config/elasticsearch.yml文件,增加如下配置:
# ES集群名称 cluster.name: my-application # 当前节点名称 node.name: node-1 # es7保存数据路径 path.data: /opt/es/data # es7程序日志路径 path.logs: /opt/es/logs # 是否开启内存锁 测试环境可不开启 bootstrap.memory_lock: false # http接口绑定的IP,0.0.0.0表示绑定任何IP network.host: 0.0.0.0 # http开放接口 http.port: 9200 # 发现主机名称,即ES服务所在的服务器主机名称 discovery.seed_hosts: ["hostname"] # 集群初始化主节点的名称 cluster.initial_master_nodes: ["node-1"] # TCP接口绑定的IP transport.host: 0.0.0.0 # TCP接口 transport.tcp.port: 9300
编辑config/jvm.options文件,更改如下配置,设置ES堆大小:
-Xmx3g -Xms3g
编辑bin/elasticsearch文件,在文件开头增加如下配置,即设置JAVA变量
export JAVA=/usr/bin/java
编辑Linux 服务器配置
编辑/etc/security/limits.conf文件,并添加如下配置
* soft nofile 65536 * hard nofile 65536 elasticsearch - nofile 65535 * soft memlock 65535 * hard memlock 65535 elasticsearch soft memlock unlimited elasticsearch hard memlock unlimited
设置单独ElasticSearch用户
执行如下命令:
# 增加elasticsearch用户 $ useradd elasticsearch # 设置elasticsearch密码 $ passwd elasticsearch
将elasticsearch程序包、数据文件夹以及日志文件夹设置为elasticsearch用户,只有elasticsearch用户才能启动elasticsearch服务
$ chown -R elasticsearch:elasticsearch /opt/es/elasticsearch-7.12.0/ $ chown -R elasticsearch:elasticsearch /opt/es/data $ chown -R elasticsearch:elasticsearch /opt/es/logs
设置Linux服务器的限制参数
$ ulimit -n 65535
编辑/etc/sysctl.conf文件
$ vim /etc/sysctl.conf
增加如下配置:
vm.max_map_count = 262144
保存退出之后,执行如下命令重载文件:
$ sysctl -p
开放防火墙端口白名单9200(http)以及9300(tcp),如果不想开通,则直接关闭防火墙即可:
$ systemctl stop firewalld
启动ElasticSearch服务
进入ElasticSearch程序包,执行启动命令:
$ sh ./bin/elasticsearch
查看日志:
$ tail -f /opt/es/logs/my-application.log
查看服务启动成功,执行如下命令,如果有ES信息结果返回则服务启动成功:
$ curl -i http://192.168.26.128:9200/
Elasticsearch常用命令
ElasticSearch官方文档地址:Elasticsearch Guide [7.17] | Elastic
监控ES7
查看当前版本可用命令:
GET http://192.168.26.128:9200/_cat/
索引
查看所有索引命令(v表示增加表格表头信息):
GET http://192.168.26.128:9200/_cat/indices?v
或者使用如下命令(format=json表示转成JSON格式,pretty将JSON数据格式化):
GET http://192.168.26.128:9200/_cat/indices?format=json&pretty
查看指定(blog)索引信息:
GET http://192.168.26.128:9200/_cat/indices?format=json&pretty&index=blog
新增索引:
PUT http://192.168.26.128:9200/test {"settings": { # 索引设置"number_of_replicas": 1, #副本数"number_of_shards": 1 #分片数},"mappings": { # 设置mapping映射"properties": { # 设置属性值"name":{"type": "keyword"},"phone":{"type": "keyword"},"age":{"type": "integer"},"ip":{"type": "ip"},"dec":{"type": "text"},"birth":{"type": "date"}}} }
删除索引:
DELETE http://192.168.26.128:9200/test
查看指定索引的mappings映射 (pretty表示格式化JSON数据)
GET http://192.168.26.128:9200/test/_mappings?pretty
更新指定索引mappings映射:
PUT http://192.168.26.128:9200/blog/_mappings {"properties": {"create_user": {"type": "text","index": false}} }
文档
新增文档信息:
格式:http://ip:port/index/_doc/{id}
id表示文档数据唯一ID信息,可不填则使用默认ID
如果反复新增数据,则为更新。
POST http://192.168.26.128:9200/blog/_doc/1 {"tags": "标签33332","age": "35","birthdate": "2023-01-02 11:32:42" }
响应数据:
{"_index": "blog","_type": "_doc","_id": "1", # 文档数据唯一ID"_version": 1,"result": "created", # 结果状态 created为新增,update为更新"_shards": {"total": 2,"successful": 1,"failed": 0},"_seq_no": 3,"_primary_term": 2 }
查看所有(即默认分页查询数据from=0&size=10):
GET http://192.168.26.128:9200/blog/_search?pretty
分页查询:
格式:http://ip:port/index/_search?from={from}&size={size}&pretty
from:从第几条数据开始
size:查询指定数量数据
GET http://192.168.26.128:9200/blog/_search?from=2&size=2&pretty
SpringBoot集成ElasticSearch使用
Spring Data ElasticSearch官方文档:Spring Data Elasticsearch - Reference Documentation
搭建项目
引入依赖
引入SpringBoot Maven依赖:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.10</version><relativePath/> <!-- lookup parent from repository --></parent>
引入Spring Boot Data ElasticSearch依赖:
使用Spring Data操作ES数据库
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
在配置文件中配置ES配置项(当前使用的是SpringBoot 2.7.10版本,老版本配置项可能有些不一致,按照指定版本来):
spring.elasticsearch.uris=http://192.168.26.128:9200
配置索引实体类
// Lombok 注解 @Data // ES 注解,标记类为指定索引映射类 @Document(indexName = "blog") public class Blog {// 索引映射唯一ID值@Idprivate String id;// mapping映射字段,type为ES7中mapping属性的type值@Field(type = FieldType.Keyword)private String tags; @Field(type = FieldType.Integer)private Integer age; @Field(type = FieldType.Date)private String birthdate; @Field(type = FieldType.Text)private String create_user;}
配置实体操作类
ElasticsearchRepository接口为Spring Data自带的接口;
第一个泛型为索引实体类对应;
第二个泛型为索引唯一ID类型。
public interface BlogRepository extends ElasticsearchRepository<Blog, String> {}
获取索引所有数据
@Component public class ESInitialize implements CommandLineRunner { @Resourceprivate BlogRepository blogRepository; @Overridepublic void run(String... args) throws Exception {System.out.println("=======查询所有=====");Iterable<Blog> all = blogRepository.findAll();print(all);// 分页查询System.out.println("=======分页查询=====");PageRequest of = PageRequest.of(0, 5);Page<Blog> pageAll = blogRepository.findAll(of);print(pageAll);// 分页排序System.out.println("=======分页排序=====");// 按照age字段从小到大排序Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, "age"));PageRequest pageRequest = PageRequest.of(0, 10, sort);Page<Blog> all1 = blogRepository.findAll(pageRequest);print(all1);} private void print(Iterable<Blog> data) {int count = 0;Iterator<Blog> iterator = data.iterator();while (iterator.hasNext()) {Blog next = iterator.next();System.out.println(JSON.toJSONString(next));count ++;}System.out.println("The data size is " + count);} }
Spring Data提供了如下查询接口:
普通增删改查接口:
public interface CrudRepository<T, ID> extends Repository<T, ID> {<S extends T> S save(S entity); <S extends T> Iterable<S> saveAll(Iterable<S> entities); Optional<T> findById(ID id); boolean existsById(ID id); Iterable<T> findAll(); Iterable<T> findAllById(Iterable<ID> ids); long count(); void deleteById(ID id); void delete(T entity); void deleteAllById(Iterable<? extends ID> ids); void deleteAll(Iterable<? extends T> entities); void deleteAll(); }
分页 + 排序接口:
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {Iterable<T> findAll(Sort sort); Page<T> findAll(Pageable pageable); }
派生查询
需在继承ElasticsearchRepository接口类中编写条件查询:
即通过接口名称翻译成ElasticSearch 的JSON查询数据
例如:
public interface BlogRepository extends ElasticsearchRepository<Blog, String> {/* 查询 age 属性为 ages 参数的数据,* 相当于SQL语句 select * from age in (...)*/Page<Blog> findAllByAgeIsIn(Pageable pageable, Integer... ages); }
支持的关键字列表查询,见Spring Data官方表格:Spring Data Elasticsearch - Reference Documentation
注解声明式查询
需在继承ElasticsearchRepository接口类中编写条件查询:
即在接口上声明@Query注解并编写查询条件,
使用?0 ?1 ?2表示第一个参数,第二个参数以及第三个参数;
示例:
public interface BlogRepository extends ElasticsearchRepository<Blog, String> {/* 相当于ES查询条件:{"query": { "fuzzy" : { "tags" : { "value": "tags" } } }*/@Query("{\\"fuzzy\\": { \\"tags\\" : {\\"value\\":\\"?0\\" } } }")Page<Blog> searchLike(String tags, Pageable pageable);}
更多内容见Spring Data官方文档:Spring Data Elasticsearch - Reference Documentation