- 操作 ES 可以采用
SpringDataElasticSearch
- 使用 intellij IDEA 创建一个 Maven jar 工程
- 我这里就不在贴图了自行创建
添加相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</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>
添加相关配置文件
- 在
src/java/resources
中创建 application.yml
- 配置内容如下:
spring:
elasticsearch:
rest:
uris: http://139.196.183.130:9200
添加相关实体类
- 在
top.it6666.dao
下创建一个 Article
实体类,内容如下:
/**
* @author BNTang
**/
@Data
@Document(indexName = "article")
public class Article {
@Id
private String id;
@Field(store = true, type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String title;
@Field(store = true, type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String content;
@Field(store = true, type = FieldType.Integer)
private Integer read;
@Field(store = true, type = FieldType.Keyword)
private String types;
@Field(store = true, type = FieldType.Keyword)
private String author;
}
- Spring Data 通过注解来声明字段的映射属性
- 有下面的三个注解来完成的:
注解名称 |
作用 |
@Document |
标记实体类为文档对象 |
@Id |
标记一个字段作为主键 |
@Field |
标记为文档中的那个的字段进行映射 |
相关注解详解
@Document
- 标记在类上,标记实体类为文档对象,一般有四个属性,如下:
indexName
:对应索引库的名称,指定那个索引
type
:索引的类型
shards
:分片数量,默认为 5
replicas
:副本数量,默认为 1
@Id
@Field
- 标记在成员变量上,标记为文档中的那个的字段,并指定字段映射属性:
type
:字段类型,取值是 枚举
:FieldType
index
:是否索引,布尔类型,默认是 true
store
:是否存储,布尔类型,默认是 false
analyzer
:分词器名称:ik_max_word
searchAnalyzer
:搜索时的分词器名称
Dao层
- 在
top.it6666.mapper
中创建一个 ArticleDao
接口
/**
* @author BNTang
**/
public interface ArticleDao extends ElasticsearchRepository<Article, String> {
}
Service层
- 在
top.it6666.service
中创建一个 ArticleService
类如下:
/**
* @author BNTang
*/
@Service
public class ArticleService {
@Autowired
private ArticleDao articleDao;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具