首先,在pom.xml
文件中添加Spring Boot和Elasticsearch的依赖:
org.springframework.boot spring-boot-starter-data-elasticsearch org.elasticsearch.client elasticsearch-rest-high-level-client 7.16.0
在application.properties
或application.yml
文件中配置Elasticsearch连接信息:
使用application.properties
配置:
# Elasticsearch properties spring.elasticsearch.rest.uris=http://localhost:9200
使用application.yml
配置:
spring: elasticsearch: rest: uris: http://localhost:9200
定义一个简单的实体类,作为索引中的文档:
import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "books", createIndex = true) public class Book { @Id private String id; private String title; private String author; // 省略构造函数、getter和setter }
创建一个接口来定义对Elasticsearch的操作:
import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface BookRepository extends ElasticsearchRepository { List findByTitle(String title); @Query("{\"match\": {\"author\": \"?0\"}}") List findByAuthorQuery(String author); }
在服务类或控制器中使用BookRepository
进行CRUD操作:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/books") public class BookController { @Autowired private BookRepository bookRepository; @PostMapping public Book addBook(@RequestBody Book book) { return bookRepository.save(book); } @GetMapping("/{id}") public Book getBook(@PathVariable String id) { return bookRepository.findById(id).orElse(null); } @PutMapping("/{id}") public Book updateBook(@PathVariable String id, @RequestBody Book book) { book.setId(id); // 设置要更新的文档的ID return bookRepository.save(book); } @DeleteMapping("/{id}") public void deleteBook(@PathVariable String id) { bookRepository.deleteById(id); } @GetMapping("/title/{title}") public List findByTitle(@PathVariable String title) { return bookRepository.findByTitle(title); } @GetMapping("/author/{author}") public List findByAuthor(@PathVariable String author) { return bookRepository.findByAuthorQuery(author); } }
Book
类:使用@Document
注解指定了索引名称和是否自动创建索引。BookRepository
接口:继承自ElasticsearchRepository
,定义了一些基本的查询方法和自定义的查询方法。BookController
类:使用BookRepository
进行CRUD操作的示例控制器,包括添加、获取、更新和删除文档,以及根据标题和作者进行查询。elasticsearch-rest-high-level-client
版本,并进行相应的依赖管理。通过这些步骤,你可以在Spring Boot应用程序中轻松地集成Elasticsearch,并实现对其的CRUD操作。