Spring Boot 集成 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. 配置 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 节点地址。

  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. 定义 ElasticSearch 操作接口

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

例如:

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

注意: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();
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愚公搬程序

你的鼓励将是我们最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值