这里只涉及到基础使用
- 导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 配置
application.yml
server:
port: 8069
spring:
data:
elasticsearch:
cluster-nodes: 127.0.0.1:9300 #配置java访问elasticsearch端口
repositories:
enabled: true
cluster-name: elasticsearch #需与elasticsearch配置文件的名字一致,也可以不配置
- 创建普通的entity
@Data
@Document(indexName = "索引名称(只能小写)",type = "类型名")
public class Study{
private Integer id;
private String name;
private String sex;
private Integer age;
}
- 创建仓库
StudyRepository
并继承ElasticsearchCrudRepository<Study, Integer>
public interface StudyRepository extends ElasticsearchCrudRepository<Study, Integer> {
}
- 创建service和实现类,以及Controller
public interface StudyService {
Study save(Study study);
void delete(Integer id);
Study update(Study study);
Study get(Integer id);
Page<Study> getAll(String name,Pageable pageable);
}
@Service
@RequiredArgsConstructor
public class StudyServiceImpl implements StudyService {
private final StudyRepository studyRepository;
private final ElasticsearchTemplate elasticsearchTemplate;
@Override
public Study save(Study study) {
return studyRepository.save(study);
}
@Override
public void delete(Integer id) {
studyRepository.deleteById(id);
}
@Override
public Study update(Study study) {
Optional<Study> studyOptional = studyRepository.findById(study.getId());
studyOptional.ifPresent(s -> {
studyRepository.save(study);
});
return study;
}
@Override
public Study get(Integer id) {
return studyRepository.findById(id).orElse(null);
}
/**
* 根据name查询(使用template进行复杂查询)
*/
@Override
public Page<Study> getAll(String name, Pageable pageable) {
NativeSearchQueryBuilder query = new NativeSearchQueryBuilder().withPageable(pageable);
if (!StringUtils.isEmpty(name)) {
query.withQuery(QueryBuilders.matchQuery("name", name));
}
NativeSearchQuery buildQuery = query.build();
List<Study> studies = elasticsearchTemplate.queryForList(buildQuery , Study.class);
return new PageImpl<>(studies);
}
注意:
-
目前
ElasticSearch
没有7.2的jar包~~使用7.2会报找不到nodes,建议降低版本~ -
ElasticSearch
提供的可视化工具Kibana
的版本必须与你安装的ElasticSearch
版本一一对应,不然无法启动~