-
添加依赖
在 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
相关推荐
vipxieliang5 天前
ValidX 在 DDD 领域驱动设计中的实践kybs19915 天前
全球灾害数据分析可视化 毕业设计-附源码66794Elasticsearch5 天前
Elastic Observability 的跨项目搜索:通过一个查询搜索所有关联项目码兄科技5 天前
24小时自助健身房系统软件开发实战指南:功能设计与部署方案paopaokaka_luck5 天前
智慧社区综合服务小程序(人脸识别、AI问答、Echarts图形化分析)需要8265 天前
JVM 内存区域与对象创建:一次 GC 从哪来Elasticsearch5 天前
Elasticsearch 中的 agentic 工作流:暂停 AI agent 等待人工审批,72 小时后恢复凤山老林5 天前
Spring Boot 应用 JVM 性能调优实战:GC 日志分析、堆内存规划与容器环境避坑计算机毕设定制辅导-无忧学长5 天前
《基于Vue的流浪动物救助中心管理系统的设计与实现》