springboot2.x 整合 elasticsearch 创建索引的方式

已经在上一篇文件讲述了springboot整合elasticsearch时,包括elasticsearch的搭建,springboot整合到elasticsearch。

 

文章地址:springboot整合elasticsearch5.x以及IK分词器做全文检索_天大会下雨的博客-CSDN博客_springboot集成ik分词器

这里我将讲述springboot 整合elasticsearch 创建索引的方式。

elasticsearch创建索引,是有很多种方式的。

比如常用的是使用postman提交put请求,我的上一篇文章就是用这种方法。

现在介绍第二种,比较合适项目开发的创建索引的方式:

1: 新建索引实体类

package com.gosuncn.esdemo.domin;


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

/**
 * 这个创建索引的过程,最主要是从 @Document 注解中的 createIndex = false 这个属性开始,
 *      因为 createIndex默认是true, 所以项目启动的时候,默认就会初始化这个索引,(但是此时还没有加 settings 等设置)
 *      所以,就必须把它设置为 false。
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "local_library", type = "book", shards = 4, createIndex = false)
public class Library {
    /**
     *     index:是否设置分词
     *     analyzer:存储时使用的分词器
     *          ik_max_word
     *          ik_word
     *     searchAnalyze:搜索时使用的分词器
     *     store:是否存储
     *     type: 数据类型
     */
    @Id
    @Field(type = FieldType.Integer)
    private Integer book_id;

    @Field(store = true, analyzer = "myanalyzer", type = FieldType.text)
    private String book_code;

    @Field(store = true, analyzer = "myanalyzer", type = FieldType.text)
    private String book_name;

    @Field(store = true, analyzer = "myanalyzer", type = FieldType.Integer)
    private Integer book_price;

    @Field(store = true, analyzer = "myanalyzer", type = FieldType.text)
    private String book_author;

    @Field(store = true, analyzer = "myanalyzer", type = FieldType.text)
    private String book_desc;

}

看到类的头部注解信息,如注解信息所示。 在启动项目时,如果 @Document 注解中的  createIndex属性为true,它会自动创建索引。 所有我这里要设置它为false,禁止它自己创建索引。

2: 新建索引

在项目启动的时候,判断是否已经存在索引了,如果不存在就新建。

package com.gosuncn.esdemo.init;

import com.gosuncn.esdemo.constant.EsData;
import com.gosuncn.esdemo.domin.Library;
import com.sun.org.apache.xml.internal.security.Init;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @ClassName: InitIndex
 * @Create By: chenxihua
 * @Author: Administrator
 * @Date: 2019/11/29 10:15
 **/
@Component
@Order(value = 0)
public class InitIndex implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(InitIndex.class);

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 项目启动的时候,如果elasticsearch已经存有索引,则不做任何操作
     *      如果没有索引,则新建索引
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        boolean indexExists = elasticsearchTemplate.indexExists(Library.class);
        if (indexExists){
            logger.warn("存在索引");
        }else {
            logger.warn("索引不存在。。。");
            try {
                boolean index = elasticsearchTemplate.createIndex(Library.class, EsData.DEFAULT_SETTING);
                boolean putMapping = elasticsearchTemplate.putMapping(Library.class);
                if (index && putMapping){
                    logger.info("索引创建成功。。。");
                }else {
                    logger.warn("索引创建失败。。。");
                }
            }catch (Exception e){
                logger.error("error: {}", e.getLocalizedMessage());
            }
        }
    }
}

这里是使用了 elasticsearchTemplate 里面的方法。 elasticsearchTemplate里面有很多方法是很好用的。如图:

然后索引中的setting设置如下:

/**
 * @ClassName: EsData
 * @Create By: chenxihua
 * @Author: Administrator
 * @Date: 2019/11/29 10:24
 *
 * 这里设置默认常量
 *
 **/
public class EsData {

    /**
     * 记录一次我设置的setting, 其实在 DEFAULT_SETTING 的最外层,是不再需要 {\"setting\"} 的了
     */
    public static final String DEFAULT_SETTING = "{" +
        "\"analysis\": {" +
            "\"analyzer\": {" +
                "\"myanalyzer\": {" +
                    "\"tokenizer\": \"mytokenizer\"" +
                "}" +
            "}," +
            "\"tokenizer\": {" +
                "\"mytokenizer\": {" +
                    "\"type\": \"ngram\"," +
                    "\"min_gram\": 1," +
                    "\"max_gram\": 2," +
                    "\"token_chars\": [" +
                        "\"letter\"," +
                        "\"digit\"," +
                        "\"whitespace\"," +
                        "\"punctuation\"," +
                        "\"symbol\"" +
                    "]" +
                "}" +
            "}" +
        "}" +
    "}";


}

这样就可以完成 elasticsearch中创建索引的时候,自定义settings的设置了。

要了解我的这篇博客,请看我的第一篇博客《springboot整合elasticsearch5.x以及IK分词器做全文检索》
上一篇的创建索引方式,是使用postman的put方式,这种方式,不符合生产环境。 所以这篇文章,将创建索引的方式,整合到项目启动时候创建自定义的方式。

希望此文帮助到你!

 

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值