用springboot+es实现查询
时间: 2024-02-01 17:02:09 浏览: 87
springboot+es 实现基本的 es的基本功能
以下是使用Spring Boot和Elasticsearch进行查询的步骤:
1. 在pom.xml文件中添加Elasticsearch的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 创建一个Elasticsearch配置类,并配置Elasticsearch的主机和端口:
```
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.demo.repository")
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Bean
public RestHighLevelClient client() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client());
}
}
```
3. 创建一个实体类,并使用@Document注解将其映射到Elasticsearch中的索引:
```
@Document(indexName = "books")
public class Book {
@Id
private String id;
private String title;
private String author;
private String description;
// getters and setters
}
```
4. 创建一个Repository接口,继承ElasticsearchRepository:
```
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> findByTitle(String title);
}
```
5. 在Controller中注入BookRepository,并使用它进行查询:
```
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookRepository bookRepository;
@GetMapping("/search")
public List<Book> search(@RequestParam String title) {
return bookRepository.findByTitle(title);
}
}
```
这样就可以使用Spring Boot和Elasticsearch进行查询了。在浏览器中访问http://localhost:8080/books/search?title=xxx,即可返回与指定标题匹配的书籍列表。
阅读全文