-
添加依赖
在 pom.xml 中添加以下依赖:org.springframework.boot spring-boot-starter-data-elasticsearch -
配置 Elasticsearch
在 application.properties 中配置 Elasticsearch 连接信息:spring.elasticsearch.uris=http://localhost:9200
-
创建实体类
使用 @Document 注解标记实体类:import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;@Document(indexName = "products")
public class Product {
@Id
private String id;
@Field(type = FieldType.Text, name = "name")
private String name;
@Field(type = FieldType.Double, name = "price")
private double price;
@Field(type = FieldType.Date, name = "created_at")
private Date createdAt;// Getters and Setters}
-
创建 Repository 接口
继承 ElasticsearchRepository 接口:import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
} -
使用 Repository
在服务类中注入 ProductRepository 并使用:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class ProductService {@Autowired private ProductRepository productRepository; public void saveProduct(Product product) { productRepository.save(product); } public Product findProductById(String id) { return productRepository.findById(id).orElse(null); }}
-
测试
编写测试类验证 Elasticsearch 集成:import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ProductServiceTest {@Autowired private ProductService productService; @Test public void testSaveAndFindProduct() { Product product = new Product(); product.setId("1"); product.setName("Laptop"); product.setPrice(1200.0); productService.saveProduct(product); Product foundProduct = productService.findProductById("1"); System.out.println(foundProduct.getName()); }}
-
总结
依赖: 添加 spring-boot-starter-data-elasticsearch 依赖。
配置: 在 application.properties 中配置 Elasticsearch 连接信息。
实体类: 使用 @Document 注解标记实体类。
Repository: 继承 ElasticsearchRepository 接口。
使用: 在服务类中注入并使用 Repository。
Springboot整合ES
未发哦京东发2025-02-15 16:18
相关推荐
core51213 小时前
Elasticsearch 车牌号片段搜索:n-gram 倒排索引实战方案এ慕ོ冬℘゜14 小时前
ES Promise.all/ Promise.race9527!到!15 小时前
Springboot @value读取配置参数踩坑&推荐解决方案十年Java程序媛15 小时前
Java 面试常问 this、super:构造方法调用顺序避坑Sayai16 小时前
Elasticsearch 日志写入链路调优实战:ingest pipeline 补时间戳、时区偏移修复与按值类型路由(附 translog 实测)总爱写点小BUG18 小时前
git-tidy:一个把「提交规范治理」做成闭环的 Git 桌面客户端小蒜学长18 小时前
基于SpingBoot+Vue的定向越野赛事管理系统的设计与开发(代码+数据库+LW)RuoyiOffice19 小时前
项目预算和交付日期变了,为什么不能直接改台账?小蒜学长19 小时前
基于过程性评价的ai助学平台(代码+数据库+LW)博风19 小时前
使用Spring官网下载Springboot骨架