-
添加依赖
在 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
相关推荐
2601_9537208214 小时前
【计算机毕业设计】基于Vue与Spring Boot的高校兼职信息服务平台设计与实现evans在进步16 小时前
Spring Boot 核心机制详解:可执行 JAR、CORS、静态资源与配置绑定Sayuanni%316 小时前
SpringBoot 从注解到源码:核心知识点总结m0_5873830018 小时前
社区家政系统开发实战:从需求分析到上线部署全指南凤山老林18 小时前
动态 i18n 体系落地:Spring Boot 多租户热加载与前后端协同实践【赫兹威客】浩哥19 小时前
基于SpringBoot+Vue3的健身运动管理系统|WebSocket实时消息 健身房毕设项目凤山老林19 小时前
数据库读写分离与动态路由实战:Spring Boot + ShardingSphere-JDBC 生产配置RuoyiOffice20 小时前
SpringBoot3+Vue3 代码生成器深拆:元数据 IR、模板编译与安全同步paopaokaka_luck21 小时前
基于springboot3+vue3的支教志愿者管理系统(AI问答、协同过滤算法、Echarts图形化分析)2601_963870181 天前
【计算机毕业设计】基于Vue+Spring Boot的助农电商系统的设计与实现