• spring-boot 2.3.x 整合elasticsearch


    spring-boot 2.3.x 整合elasticsearch


    本地项目的基础环境

    环境版本
    jdk1.8.0_201
    maven3.6.0
    Spring-boot2.3.3.RELEASE
    elasticsearch7.8.0

    1、elasticsearch的安装(docker形式)

    这里使用docker,做一个快速的单机版本安装,需要更详细的其他形式的安装,可以查看其他的相关资料或者官网地址

    《官网文档-elasticsearch》

    《docker-hub-elasticsearch》

    《docker、docker-compose 下安装elasticsearch、IK分词器》

    《docker、docker-compose 下安装kibana》

    1.1、docker-compose.yml

    version: '3.1'
    services:
      es01:
        image: docker.elastic.co/elasticsearch/elasticsearch:7.8.0
        container_name: es01
        environment:
          - discovery.type=single-node
        volumes:
          - /Users/liqi/docker-compose/elasticsearch/data:/usr/share/elasticsearch/data
          - /Users/liqi/docker-compose/elasticsearch/plugins:/usr/share/elasticsearch/plugins
          - /Users/liqi/docker-compose/elasticsearch/config:/usr/share/elasticsearch/config
        ports:
          - 9200:9200
          - 9300:9300
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2、构建一个elasticsearch的项目badger-spring-boot-elasticsearch

    主要是导入spring-boot-starter-data-elasticsearch的包;

    
    <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
        xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.3.3.RELEASEversion>
            <relativePath /> 
        parent>
        <groupId>com.badgergroupId>
        <artifactId>badger-spring-boot-elasticsearchartifactId>
        <version>0.0.1-SNAPSHOTversion>
        <name>badger-spring-boot-elasticsearchname>
        <properties>
            <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
            <java.version>1.8java.version>
            <maven-jar-plugin.version>3.1.1maven-jar-plugin.version>
        properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-elasticsearchartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>fastjsonartifactId>
                <version>1.2.76version>
            dependency>
        dependencies>
        <build>
            <plugins>
                
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
    project>
    
    
    • 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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    3.1、定义yml配置文件

    spring:
      elasticsearch:
        rest:
          uris:
          - http://127.0.0.1:9200
    
    • 1
    • 2
    • 3
    • 4
    • 5

    org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties.class具体更可以参看配置类;

    配置属性为

    /**
     * Configuration properties for Elasticsearch REST clients.
     *
     * @author Brian Clozel
     * @since 2.1.0
     */
    @ConfigurationProperties(prefix = "spring.elasticsearch.rest")
    public class ElasticsearchRestClientProperties {
    
    	/**
    	 * Comma-separated list of the Elasticsearch instances to use.
    	 */
    	private List<String> uris = new ArrayList<>(Collections.singletonList("http://localhost:9200"));
    
    	/**
    	 * Credentials username.
    	 */
    	private String username;
    
    	/**
    	 * Credentials password.
    	 */
    	private String password;
    
    	/**
    	 * Connection timeout. 链接超时
    	 */
    	private Duration connectionTimeout = Duration.ofSeconds(1);
    
    	/**
    	 * Read timeout. 链接后,返回数据的读超时
    	 */
    	private Duration readTimeout = Duration.ofSeconds(30);
    
    • 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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    3.2、定义es的对应的实体

    /**
     * es存库的实体
     * @author liqi
     * @data 2022年5月16日 下午4:20:33
     */
    @Document(indexName = "test_product", shards = 3)
    @Data
    public class SearchProduct implements Serializable {
    
        private static final long serialVersionUID = -6629478619791342054L;
    
        /**主键*/
        @Id
        private Integer id;
    
        /**skuId*/
        @Field(type = FieldType.Keyword)
        private String skuId;
    
        /**名称1*/
        @Field(type = FieldType.Text, analyzer = "ik_smart")
        private String name;
    
        /**价格*/
        private Double price;
    
    }
    
    
    • 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
    • 27
    • 28

    @Id注解:必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id";

    @Field注解:

    • type : 字段数据类型
    • analyzer : 分词器类型
    • index : 是否索引(默认:true)
    • Keyword : 短语,不进行分词

    3.3、定义es的CrudRepository

    /**
     * es dao
     * @author liqi
     *
     */
    public interface SearchProductDao extends ElasticsearchRepository<SearchProduct, Integer> {
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    可以看到,自定义的SearchProductDao.class 继承了ElasticsearchRepository.class

    /**
     * @param 
     * @param 
     * @author Rizwan Idrees
     * @author Mohsin Husen
     * @author Sascha Woo
     * @author Murali Chevuri
     * @author Peter-Josef Meisch
     */
    @NoRepositoryBean
    public interface ElasticsearchRepository<T, ID> extends PagingAndSortingRepository<T, ID> {
    
    	/**
    	 * @deprecated since 4.0, use {@link #save(Object)} instead
    	 */
    	@Deprecated
    	default <S extends T> S index(S entity) {
    		return save(entity);
    	}
    
    	/**
    	 * This method is intended to be used when many single inserts must be made that cannot be aggregated to be inserted
    	 * with {@link #saveAll(Iterable)}. This might lead to a temporary inconsistent state until {@link #refresh()} is
    	 * called.
    	 * 
    	 * @deprecated since 4.0, use a custom repository implementation instead
    	 */
    	@Deprecated
    	<S extends T> S indexWithoutRefresh(S entity);
    
    	/**
    	 * @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
    	 *             {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
    	 */
    	Iterable<T> search(QueryBuilder query);
    
    	/**
    	 * @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
    	 *             {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
    	 */
    	Page<T> search(QueryBuilder query, Pageable pageable);
    
    	/**
    	 * @deprecated since 4.0, use standard repository method naming or @{@link Query} annotated methods, or
    	 *             {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations}.
    	 */
    	Page<T> search(Query searchQuery);
    
    	/**
    	 * Search for similar entities using a morelikethis query
    	 * 
    	 * @param entity the entity for which similar documents should be searched, must not be {@literal null}
    	 * @param fields
    	 * @param pageable , must not be {@literal null}
    	 * @return
    	 */
    	Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable);
    
    	/**
    	 * @deprecated since 4.0, use {@link IndexOperations#refresh(Class)} instead. Repository methods should call refresh
    	 *             in their implementation.
    	 */
    	@Deprecated
    	void refresh();
    }
    
    • 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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    1、其中泛型表示使用的实体;

    2、泛型表示的主键的类型;

    3、ElasticsearchRepository.class继承了PagingAndSortingRepositoryPagingAndSortingRepositor.class类是在spring-data包下了,具体怎么使用,就不再详细解释这个标准了;

    3.4、主启动类

    @SpringBootApplication
    public class ElasticsearchApplicaltion {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(ElasticsearchApplicaltion.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、测试代码

    4.1、查看当前es的索引

    GET _cat/indices?v
    
    • 1

    可以看到,没有我们实体上的索引test_product,只有之前的我测试的product

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { ElasticsearchApplicaltion.class })
    public class AppTest {
    
        @Autowired
        SearchProductDao searchProductDao;
    
        @Test
        public void save() {
            List<SearchProduct> list = new ArrayList<SearchProduct>();
            String names = "中天\n" + "敏杨\n" + "名爵尔\n" + "万宝龙\n" + "万宝龙\n" + "巴黎水";
            String[] split = names.split("\n");
            for (int i = 0; i < split.length; i++) {
                SearchProduct searchProduct = new SearchProduct();
                searchProduct.setId(i + 1);
                searchProduct.setName(split[i]);
                searchProduct.setSkuId("sku" + split[i]);
                searchProduct.setPrice(i + 0.1D);
                list.add(searchProduct);
            }
            searchProductDao.saveAll(list);
        }
        @Test
        public void search() {
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            // 搜索关键词
            builder.must(QueryBuilders.matchQuery("name", "中天"));
            Iterable<SearchProduct> search = searchProductDao.search(builder);
            for (SearchProduct searchProduct : search) {
                System.out.println(JSON.toJSONString(searchProduct));
            }
        }
    }
    
    
    • 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
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    《官网文档-elasticsearch》

    《docker-hub-elasticsearch》

    《docker、docker-compose 下安装elasticsearch、IK分词器》

    《docker、docker-compose 下安装kibana》

    详细代码也可以参看《码云》

  • 相关阅读:
    SQL 常见函数整理 _ PATINDEX
    如何开发LAXCUS分布式应用软件(一)
    新手小白看过来——带你快速入门跨境电商
    golang中的错误处理
    CAPL学习之路-诊断函数
    ubuntu 22.04版本修改时区的操作方法
    E117-经典赛题-主机发现与信息收集
    苹果ios企业签名永不掉签免签网页封装应用解决方案
    导师邀请你继续跟他读博,你会不会立马答应?
    Effective C++ 改善程序与设计的55个具体做法笔记与心得 2
  • 原文地址:https://blog.csdn.net/qq_28410283/article/details/126537731