一、准备工作

官网下载Elasticsearch,我们选用6.18.12这个版本。

https://www.elastic.co/cn/downloads/past-releases/elasticsearch-6-8-12

分词器也下载6.18.12版本。

https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v6.8.12

下载好之后解压,把分词器复制到Elasticsearch下的plugins目录ik下。

SpringBoot集成Elasticsearch入门_elasticsearch

进入Elasticsearch的bin目录下,运行elasticsearch.bat,访问http://localhost:9200

SpringBoot集成Elasticsearch入门_elasticsearch_02

看到这个页面显示,说明我们的Elasticsearch已经启动成功了。

二、集成SpringBoot

1.添加依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.创建Elasticsearch对象

package com.example.dockerdemo.bean;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.Date;

/**
 * @author qx
 * @date 2023/7/31
 * @des Elasticsearch对象
 */
@Data
@Document(indexName = "book", createIndex = true)
public class Book {

    @Id
    @Field(type = FieldType.Long)
    private Long id;

    @Field(analyzer = "ik_max_word")
    private String title;

    @Field(analyzer = "ik_max_word")
    private String author;

    @Field(type = FieldType.Double)
    private Double price;
}

@Document:用来标识文档实体类,indexName属性用来指定索引名称,createIndex=true表示自动创建索引,默认为true。

@Id用来指定索引的Id字段。

@Field用来标识文档的字段,analyzer用来指定索引的分词器。type指定属性的类型。

3.Elasticsearch客户端配置类

package com.example.dockerdemo.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

/**
 * @author qx
 * @date 2023/7/31
 * @des Elasticsearch客户端配置类
 */
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
    @Bean
    @Override
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

4.创建Elasticsearch Repositories

package com.example.dockerdemo.repository;

import com.example.dockerdemo.bean.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * @author qx
 * @date 2023/7/31
 * @des
 */
public interface ESBookRepository extends ElasticsearchRepository<Book, Long> {

    List<Book> findByTitleOrAuthor(String title, String author);
}

5.创建服务层

package com.example.dockerdemo.service;

import com.example.dockerdemo.bean.Book;
import com.example.dockerdemo.repository.BookRepository;
import com.example.dockerdemo.repository.ESBookRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author qx
 * @date 2023/7/31
 * @des 服务层
 */
@Slf4j
@Service
public class BookService {

    @Autowired
    private ESBookRepository esBookRepository;

    public void addBook(Book book) {
        try {
            esBookRepository.save(book);
        } catch (Exception e) {
            log.error("保存es错误");
        }
    }

    public List<Book> searchBook(String keyword) {
        return esBookRepository.findByTitleOrAuthor(keyword, keyword);
    }

}

6.创建控制层

package com.example.dockerdemo.controller;

import com.example.dockerdemo.bean.Book;
import com.example.dockerdemo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author qx
 * @date 2023/7/31
 * @des
 */
@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    private BookService bookService;

    /**
     * 添加数据
     *
     * @param book 对象
     * @return
     */
    @PostMapping("/addBook")
    public String addBook(@RequestBody Book book) {
        bookService.addBook(book);
        return "success";
    }

    /**
     * 根据关键字搜索
     *
     * @param keyword 关键字
     * @return 列表
     */
    @GetMapping("/searchBook")
    public List<Book> searchBook(String keyword) {
        return bookService.searchBook(keyword);
    }

}

7.测试

我们添加几条测试数据

SpringBoot集成Elasticsearch入门_elasticsearch_03

SpringBoot集成Elasticsearch入门_分词器_04

然后我们在浏览器上传入关键字查询数据

SpringBoot集成Elasticsearch入门_elasticsearch_05

SpringBoot集成Elasticsearch入门_elasticsearch_06