ElasticSearch 是一个基于 Lucene 搜索引擎的分布式、开源搜索和分析引擎。Spring Boot 集成 ElasticSearch 可以通过 ElasticsearchTemplate 或者 Spring Data Elasticsearch。
下面以 Spring Data Elasticsearch 为例介绍 Spring Boot 集成 ElasticSearch 的步骤:
- 添加 Spring Boot Starter Data Elasticsearch 依赖
在项目的 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 配置 ElasticSearch
在 application.yml 文件中添加 ElasticSearch 的配置:
spring:
data:
elasticsearch:
cluster-name: mycluster
cluster-nodes: 192.168.1.1:9300,192.168.1.2:9300
注:cluster-name 表示 ElasticSearch 集群的名称,cluster-nodes 表示 ElasticSearch 节点地址。
- 定义实体类
定义实体类,并使用 @Document 注解来标记其是一个文档类,并指定其在 ElasticSearch 中的索引名称和类型名称。
例如:
@Document(indexName = "book", type = "novel")
public class Book {
@Id
@Field(type = FieldType.Long)
private Long id;
@Field(type = FieldType.Keyword)
private String name;
@Field(type = FieldType.Keyword)
private String author;
@Field(type = FieldType.Integer)
private Integer wordCount;
@Field(type = FieldType.Date)
private Date createTime;
//省略getter和setter方法
}
- 定义 ElasticSearch 操作接口
定义 ElasticSearch 操作接口,继承 ElasticsearchRepository 接口。
例如:
public interface BookRepository extends ElasticsearchRepository<Book, Long> {
}
注意:ElasticsearchRepository 接口已经提供了大量的数据存储和查询方法,无需手动实现。
- 使用 ElasticSearch 操作接口
在需要使用 ElasticSearch 操作接口的地方注入即可。
例如:
@RestController
public class BookController {
@Autowired
private BookRepository bookRepository;
@GetMapping("/book/{id}")
public Book getBookById(@PathVariable Long id) {
return bookRepository.findById(id).orElse(null);
}
@PostMapping("/book")
public Book addBook(@RequestBody Book book) {
return bookRepository.save(book);
}
@DeleteMapping("/book/{id}")
public void deleteBookById(@PathVariable Long id) {
bookRepository.deleteById(id);
}
@GetMapping("/books")
public Iterable<Book> getAllBooks() {
return bookRepository.findAll();
}
}
以上就是 Spring Boot 集成 ElasticSearch 的基本步骤。