SpringBoot整合elasticsearch
时间: 2023-08-25 08:07:44 浏览: 193
SpringBoot整合Elasticsearch7.2.0的实现方法
4星 · 用户满意度95%
好的,下面是SpringBoot整合elasticsearch的步骤:
1. 引入elasticsearch和spring-boot-starter-data-elasticsearch的依赖:
```
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.12.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.4.5</version>
</dependency>
```
2. 配置elasticsearch连接信息:
```
spring.data.elasticsearch.cluster-nodes=localhost:9200
```
3. 创建实体类:
```
@Document(indexName = "my_index")
public class MyEntity {
@Id
private String id;
private String name;
// getter and setter
}
```
4. 创建es的Repository:
```
public interface MyRepository extends ElasticsearchRepository<MyEntity, String> {
}
```
5. 在service中使用Repository:
```
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
public void save(MyEntity entity) {
myRepository.save(entity);
}
public List<MyEntity> search(String name) {
return myRepository.findByName(name);
}
}
```
6. 在controller中调用service:
```
@RestController
public class MyController {
@Autowired
private MyService myService;
@PostMapping("/save")
public void save(@RequestBody MyEntity entity) {
myService.save(entity);
}
@GetMapping("/search")
public List<MyEntity> search(@RequestParam String name) {
return myService.search(name);
}
}
```
这样就可以通过SpringBoot整合elasticsearch实现数据的增删改查了。
阅读全文