-
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
在 pom.xml 中添加以下依赖: -
配置 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
相关推荐
risc1234566 分钟前
【Elasticsearch】如何获取一致的评分典龙3306 小时前
如何使用springboot项目如何实现小程序里面商品的浏览记录功能案例customer087 小时前
【开源免费】基于SpringBoot+Vue.JS个人博客系统(JAVA毕业设计)qq_459238497 小时前
SpringBoot整合Redis和Redision锁灰色人生qwer7 小时前
SpringBoot 项目配置日志输出2301_793069827 小时前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)Earth explosion7 小时前
Spring Boot:开启快速开发新时代hhw1991127 小时前
spring boot知识点5customer088 小时前
【开源免费】基于SpringBoot+Vue.JS打卡健康评测系统(JAVA毕业设计)ONEPEICE-ing9 小时前
快速入门Springboot+vue——MybatisPlus多表查询及分页查询