springboot+es的demo
时间: 2023-08-23 12:54:19 浏览: 110
springboot的demo
这里是一个基于Spring Boot和Elasticsearch的简单示例,可以帮助你快速入门:
1. 首先,你需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 在application.properties文件中添加Elasticsearch的配置:
```properties
spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9300
```
3. 创建一个Elasticsearch实体类,例如:
```java
@Document(indexName = "blog", type = "article")
public class Article {
@Id
private Long id;
private String title;
private String content;
// 省略getter和setter方法
}
```
4. 创建一个Elasticsearch的Repository接口,例如:
```java
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
List<Article> findByTitle(String title);
List<Article> findByContent(String content);
}
```
5. 在Spring Boot的启动类中添加@EnableElasticsearchRepositories注解,启用Elasticsearch的Repository:
```java
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.example.elasticdemo.repository")
public class ElasticDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ElasticDemoApplication.class, args);
}
}
```
6. 在Controller中使用Elasticsearch的Repository进行CRUD操作,例如:
```java
@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleRepository articleRepository;
@PostMapping("/")
public Article save(@RequestBody Article article) {
return articleRepository.save(article);
}
@GetMapping("/{id}")
public Article getById(@PathVariable Long id) {
Optional<Article> article = articleRepository.findById(id);
return article.orElse(null);
}
@GetMapping("/search/{keyword}")
public List<Article> search(@PathVariable String keyword) {
List<Article> articles = articleRepository.findByTitle(keyword);
articles.addAll(articleRepository.findByContent(keyword));
return articles;
}
}
```
这就是一个基于Spring Boot和Elasticsearch的简单示例,希望可以帮助你快速入门。
阅读全文