【SpringCloud学习笔记】Elasticsearch
在Spring Cloud中,Elasticsearch是一个常用的搜索和分析引擎,可以用来增强应用的搜索功能。以下是一个使用Spring Data Elasticsearch的简单示例:
- 首先,在
pom.xml
中添加Spring Data Elasticsearch的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 配置Elasticsearch客户端,在
application.properties
或application.yml
中设置Elasticsearch的基本信息:
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
- 创建一个Elasticsearch实体:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "sampleindex")
public class SampleEntity {
@Id
private String id;
private String content;
// Getters and Setters
}
- 创建一个Elasticsearch仓库接口:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface SampleEntityRepository extends ElasticsearchRepository<SampleEntity, String> {
// 自定义查询方法
}
- 使用仓库进行操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SampleService {
@Autowired
private SampleEntityRepository repository;
public SampleEntity create(SampleEntity entity) {
return repository.save(entity);
}
public List<SampleEntity> findAll() {
return repository.findAll();
}
// 其他操作
}
- 使用Elasticsearch进行搜索:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class SearchService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public Page<SampleEntity> search(String query, int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.withQuery(queryStringQuery(query))
.withPageable(pageRequest);
ret
评论已关闭