Elasticsearch入门之SpringBoot整合Elasticsearch

本文介绍了如何在SpringBoot应用中整合Elasticsearch,包括添加依赖、配置文档对象、创建和删除索引、数据操作及查询方法。通过继承ElasticsearchRepository接口,可以便捷地实现CRUD操作,同时文章提供了接口测试示例,展示了如何根据价格区间和标题关键字进行查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

前面两篇文章完成了 windows 环境下 elasticsearch 的安装,这篇文章学习了解一下 elasticsearchAPI 以及简单的使用,算是入门级教程笔记

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,需要指定一个精度因子,比如 10100elasticsearch 会把真实值乘以这个因子后存储,取出时再还原
      • 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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值