-
添加依赖
在 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
相关推荐
前端 贾公子31 分钟前
Git Worktree 使用指南吴声子夜歌35 分钟前
MongoDB 4.x——SpringBoot框架整合snow@li1 小时前
Spring Boot:项目服务器完整部署教程(零基础可直接实操)Elasticsearch1 小时前
如何使用 OpenTelemetry 对你的搜索 API 进行埋点,并使用 ES|QL 对其进行查询万亿少女的梦1682 小时前
基于Spring Boot、Java与MySQL的网络订餐系统设计与实现鱟鲥鳚11 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)腾渊信息科技公司13 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案阿里云大数据AI技术14 小时前
更快、更稳、更省:揭秘阿里云 Elasticsearch 存算分离与弹性扩缩阿里云大数据AI技术16 小时前
Search Lake:ES x Paimon 让湖上多模态数据可搜可用隔窗听雨眠16 小时前
Spring Boot在云原生时代的编程范式革新研究