springboot整合es

1. 引入依赖

pom.xml 中添加 Spring Boot 和 Elasticsearch 相关的依赖:

xml


复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.10.0</version>
</dependency>

2. 配置 Elasticsearch 连接

application.ymlapplication.properties 中配置 Elasticsearch 的连接信息:

yaml


复制代码
spring:
  elasticsearch:
    uris: http://localhost:9200
    username: elastic
    password: your_password

3. 创建 Elasticsearch 实体类

你可以将需要存储到 Elasticsearch 中的对象映射为一个实体类,并使用注解进行映射。例如:

java


复制代码
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "product")
public class Product {
    @Id
    private String id;
    private String name;
    private Double price;
    private String description;

    // Getters and Setters
}

4. 创建 Elasticsearch Repository

通过 Spring Data Elasticsearch,可以直接创建一个接口来操作 Elasticsearch 索引:

java


复制代码
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    List<Product> findByName(String name);
}

5. 使用 Service 调用 Repository

创建一个服务类来使用你定义的 ProductRepository

java


复制代码
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 List<Product> searchByName(String name) {
        return productRepository.findByName(name);
    }
}

6. 使用 Elasticsearch 的全文搜索功能

你还可以自定义查询方法,比如进行全文搜索或复杂查询。通过 NativeSearchQueryBuilder 构建查询条件:

java


复制代码
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import static org.elasticsearch.index.query.QueryBuilders.*;

@Service
public class ProductService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    public List<Product> searchProducts(String keyword) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(multiMatchQuery(keyword, "name", "description"))
                .build();

        return elasticsearchTemplate.search(searchQuery, Product.class)
                                     .getSearchHits()
                                     .stream()
                                     .map(hit -> hit.getContent())
                                     .collect(Collectors.toList());
    }
}
posted @ 2024-09-07 14:04  冷风5997  阅读(45)  评论(0编辑  收藏  举报