前言
前面两篇文章完成了 windows
环境下 elasticsearch
的安装,这篇文章学习了解一下 elasticsearch
的 API
以及简单的使用,算是入门级教程笔记
SpringBoot
整合 Elasticsearch
整合环境
springboot
版本2.0.9.RELEASE
elasticsearch
版本5.6.16
Maven
依赖
主要依赖如下,其它的自行引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
application.properties
文件
server.port=8080
# 程序连接 elasticsearch 的端口号是9300
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.repositories.enabled=true
文档对象
spring-boot-starter-data-elasticsearch
提供了面向对象的方式操作 elasticsearch
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "item", type = "docs")
public class Item implements Serializable {
@Id
private Long id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title; // 标题
@Field(type = FieldType.Keyword)
private String category;// 分类
@Field(type = FieldType.Keyword)
private String brand; // 品牌
@Field(type = FieldType.Double)
private Double price; // 价格
@Field(index = false, type = FieldType.Keyword)
private String images; // 图片地址
}
@Document
:作用在类,标记实体类为文档对象indexName
:对应索引库名称type
:对应在索引库中的类型shards
:分片数量,默认5
replicas
:副本数量,默认1
@Id
:作用在成员变量,标记一个字段作为id
主键@Field
:作用在成员变量,标记为文档的字段,并指定字段映射属性type
:字段类型,是枚举:FieldType
,可以是text、long、short、date、integer、object
等text
:存储数据时候,会自动分词,并生成索引keyword
:存储数据时候,不会分词建立索引Numerical
:数值类型,分两类- 基本数据类型:
long、interger、short、byte、double、float、half_float
- 浮点数的高精度类型:
scaled_float
,需要指定一个精度因子,比如10
或100
。elasticsearch
会把真实值乘以这个因子后存储,取出时再还原
- 基本数据类型:
Date
:日期类型,elasticsearch
可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long
,节省空间
index
:是否索引,布尔类型,默认是true
store
:是否存储,布尔类型,默认是false
analyzer
:分词器名称,这里的ik_max_word
即使用ik分词器
Elasticsearch
与关系型数据库对比
关系型数据库(比如 Mysql) | 非关系型数据库(Elasticsearch) |
---|---|
数据库 Database | 索引库 Index |
表 Table | 类型 Type |
数据行 Row | 文档 Document |
数据列 Column | 字段 Field |
Elasticsearch
索引库相关操作
创建索引和映射
索引和映射的创建,需要使用 ElasticsearchTemplate
模板工具类,在需要的地方注入即可
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Override
public void createIndexAndMapping() {
// 创建索引,会根据 Item 类的 @Document 注解信息来创建
elasticsearchTemplate.createIndex(Item.class);
// 配置映射,会根据 Item 类中的 id、Field 等字段来自动完成映射
elasticsearchTemplate.putMapping(Item.class);
}
索引信息如下
删除索引
索引的删除,同样需要使用 ElasticsearchTemplate
模板工具类
@Override
public