-
添加依赖
在 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
相关推荐
Flittly4 分钟前
【AgentScope Java新手村系列】(3)工具系统Java 码思客10 分钟前
【ElasticSearch从入门到架构师】第1章:ElasticSearch 核心认知与行业定位Flittly1 小时前
【AgentScope Java新手村系列】(2)第一个Agent-基础对话小二·2 小时前
Spring Boot 3 + Vue 3 全栈开发实战码农飞哥2 小时前
Spring Boot 多角色权限隔离实战:接口层+路由层+UI层三层防御,杜绝生产数据泄露SuperArc19992 小时前
SpringBoot+Slf4j+Log4j2+mybatis 日志整合lfwh3 小时前
探针程序技术解析:基于 Spring Boot 非 Web 模式的云服务监控告警系统霸道流氓气质4 小时前
阿里云 OSS 从零到实战:概念、配置与 Spring Boot 集成指南可乐ea4 小时前
【Spring Boot + MyBatis|第4篇】MyBatis 动态 SQL:if、where、foreach 使用详解serve the people4 小时前
Elasticsearch(5) i want to monitor the es health from a http api