Springboot接入Elastic
1. 添加依赖
首先,需要在pom.xml
文件中添加Spring Data Elasticsearch的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2. 配置Elasticsearch连接
在application.properties
或application.yml
文件中配置Elasticsearch连接信息:
spring:
elasticsearch:
uris: http://localhost:9200
如果Elasticsearch需要身份验证,则添加用户名和密码:
spring:
elasticsearch:
username: your-username
password: your-password
3. 创建实体类
创建一个实体类,并使用Elasticsearch的注解来标记其映射:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "your_index_name")
public class YourEntity {
@Id
private String id;
private String field1;
private String field2;
// Getters and setters
}
4. 创建Repository接口
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface YourEntityRepository extends ElasticsearchRepository<YourEntity, String> {
// 你可以在这里定义自定义查询方法
}
5. 实现增删改查操作
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class YourEntityService {
@Autowired
private YourEntityRepository repository;
public YourEntity save(YourEntity entity) {
return repository.save(entity);
}
public Optional<YourEntity> findById(String id) {
return repository.findById(id);
}
public Iterable<YourEntity> findAll() {
return repository.findAll();
}
public void deleteById(String id) {
repository.deleteById(id);
}
public YourEntity update(String id, YourEntity updatedEntity) {
if (repository.existsById(id)) {
updatedEntity.setId(id);
return repository.save(updatedEntity);
}
return null;
}
}
6. 使用
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/entities")
public class YourEntityController {
@Autowired
private YourEntityService service;
@PostMapping
public YourEntity createEntity(@RequestBody YourEntity entity) {
return service.save(entity);
}
@GetMapping("/{id}")
public YourEntity getEntity(@PathVariable String id) {
return service.findById(id).orElse(null);
}
@GetMapping
public Iterable<YourEntity> getAllEntities() {
return service.findAll();
}
@PutMapping("/{id}")
public YourEntity updateEntity(@PathVariable String id, @RequestBody YourEntity updatedEntity) {
return service.update(id, updatedEntity);
}
@DeleteMapping("/{id}")
public void deleteEntity(@PathVariable String id) {
service.deleteById(id);
}
}