springboot+elasticsearch代码案例
时间: 2023-12-12 10:02:08 浏览: 87
以下是一个基于Spring Boot和Elasticsearch的简单代码示例:
1. 添加Maven依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置Elasticsearch连接
在application.properties文件中添加以下属性:
```
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.cluster-name=my-elasticsearch-cluster
```
3. 创建实体类
```
@Document(indexName = "user", type = "user")
public class User {
@Id
private String id;
private String name;
private int age;
// getters and setters
}
```
4. 创建Elasticsearch Repository
```
public interface UserRepository extends ElasticsearchRepository<User, String> {
List<User> findByName(String name);
}
```
5. 使用Repository进行操作
```
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/user")
public User addUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/user/{id}")
public User getUser(@PathVariable String id) {
return userRepository.findOne(id);
}
@GetMapping("/user/search")
public List<User> searchUser(@RequestParam String name) {
return userRepository.findByName(name);
}
}
```
以上代码示例演示了如何使用Spring Boot和Elasticsearch创建一个简单的用户管理系统,包括添加用户、查询用户和搜索用户。
阅读全文