当前位置:   article > 正文

Spring Boot 集成 ElasticSearch_spring-boot-starter-data-elasticsearch

spring-boot-starter-data-elasticsearch

ElasticSearch 是一个基于 Lucene 搜索引擎的分布式、开源搜索和分析引擎。Spring Boot 集成 ElasticSearch 可以通过 ElasticsearchTemplate 或者 Spring Data Elasticsearch。

下面以 Spring Data Elasticsearch 为例介绍 Spring Boot 集成 ElasticSearch 的步骤:

  1. 添加 Spring Boot Starter Data Elasticsearch 依赖

在项目的 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  1. 配置 ElasticSearch

在 application.yml 文件中添加 ElasticSearch 的配置:

spring:
  data:
    elasticsearch:
      cluster-name: mycluster
      cluster-nodes: 192.168.1.1:9300,192.168.1.2:9300
  • 1
  • 2
  • 3
  • 4
  • 5

注:cluster-name 表示 ElasticSearch 集群的名称,cluster-nodes 表示 ElasticSearch 节点地址。

  1. 定义实体类

定义实体类,并使用 @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方法
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  1. 定义 ElasticSearch 操作接口

定义 ElasticSearch 操作接口,继承 ElasticsearchRepository 接口。

例如:

public interface BookRepository extends ElasticsearchRepository<Book, Long> {
}
  • 1
  • 2

注意:ElasticsearchRepository 接口已经提供了大量的数据存储和查询方法,无需手动实现。

  1. 使用 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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

以上就是 Spring Boot 集成 ElasticSearch 的基本步骤。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/609107
推荐阅读
相关标签
  

闽ICP备14008679号