springboot elasticsearch 整合demo
时间: 2023-06-29 22:15:39 浏览: 156
好的,下面是一个简单的 Spring Boot 集成 Elasticsearch 的示例:
1. 首先,需要在 pom.xml 文件中添加 Elasticsearch 的依赖:
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.2</version>
</dependency>
```
2. 然后,在 application.yml 或 application.properties 中配置 Elasticsearch 的地址和端口:
```yaml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: localhost:9200
```
3. 创建一个实体类,用于映射 Elasticsearch 中的数据:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "user", shards = 1, replicas = 0)
public class User {
@Id
private String id;
private String name;
private Integer age;
}
```
4. 创建一个 Elasticsearch 的操作类,用于增删改查:
```java
@Component
public class ElasticsearchOperations {
private final ElasticsearchRestTemplate elasticsearchRestTemplate;
public ElasticsearchOperations(ElasticsearchRestTemplate elasticsearchRestTemplate) {
this.elasticsearchRestTemplate = elasticsearchRestTemplate;
}
public void save(User user) {
IndexQuery indexQuery = new IndexQueryBuilder()
.withIndexName("user")
.withObject(user)
.build();
elasticsearchRestTemplate.index(indexQuery);
}
public void delete(String id) {
elasticsearchRestTemplate.delete("user", id);
}
public void update(User user) {
IndexRequest indexRequest = new IndexRequest("user")
.id(user.getId())
.source(new ObjectMapper().convertValue(user, Map.class));
UpdateRequest updateRequest = new UpdateRequest("user", user.getId())
.doc(new ObjectMapper().convertValue(user, Map.class))
.upsert(indexRequest);
elasticsearchRestTemplate.update(updateRequest);
}
public List<User> search(String keyword) {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("name", keyword))
.build();
return elasticsearchRestTemplate.queryForList(searchQuery, User.class);
}
}
```
5. 最后,在 Controller 中使用 ElasticsearchOperations 进行增删改查操作:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private ElasticsearchOperations elasticsearchOperations;
@PostMapping
public void save(@RequestBody User user) {
elasticsearchOperations.save(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable String id) {
elasticsearchOperations.delete(id);
}
@PutMapping
public void update(@RequestBody User user) {
elasticsearchOperations.update(user);
}
@GetMapping
public List<User> search(@RequestParam String keyword) {
return elasticsearchOperations.search(keyword);
}
}
```
以上就是一个简单的 Spring Boot 集成 Elasticsearch 的示例。
阅读全文