spring elasticsearch:启动项目时自动创建索引

0.引言

在springboot整合spring data elasticsearch项目中,当索引数量较多,mapping结构较为复杂时,我们常常希望启动项目时能够自动创建索引及mapping,这样就不用再到各个环境中创建索引了

所以今天咱们就来看看如何自动创建索引

  1. 引入依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
  1. 创建es实体类

@Data
@Configuration
@Document(indexName = "es_log")
public class EsLogEntity {
    @Id
    @ApiModelProperty("主键id")
    @Field(type = FieldType.Keyword)
    private String id;
    /**
     * 类型名称
     */
    @ApiModelProperty(value = "类型名称")
    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String logName;
  }
  1. 利用createIndex属性实现

如股票使用的是spring data elasticsearch包,其@Document注解中包含了一个createIndex属性,默认为true,也就是默认开启了自动创建索引的,想要关闭也可通过设置为false来实现。

  1. 利用反射实现

1 因为要调用ElasticsearchRestTemplate,所以要提前声明其bean


@Configuration
@Component
public class EsConfig {

    @Value("${ES.ip}")
    private String esIp;
    @Value("${ES.port}")
    private Integer esPort;
    @Value("${ES.userName}")
    private String userName;
    @Value("${ES.password}")
    private String password;


    @Bean
    public RestHighLevelClient restHighLevelClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(esIp, esPort, "http"))
                        .setRequestConfigCallback(builder -> {
                            // 连接超时(默认为1秒)
                            builder.setConnectTimeout(10000);
                            // 套接字超时(默认为30秒)
                            builder.setSocketTimeout(60000);
                            return builder;
                        })
                        .setHttpClientConfigCallback(builder -> {
                            // 线程数
                            return builder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
//                             builder;
                        })
                //密码访问
                .setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider))
        );
    }
}

2 首先要获取所有添加@Document注解的实体类,我们需要通过Reflections类来实现

添加依赖

<dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
</dependency>

获取方法如下,其中com.xxx.xxx.entity是实体类的包名

Reflections f = new Reflections("com.xxx.xxx.entity");
Set<Class<?>> classSet = f.getTypesAnnotatedWith(Document.class);

3 创建项目启动后调用的配置类


@Configuration
@Slf4j
@AllArgsConstructor
public class ElasticSearchStartCreateIndex implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("[elastic]索引初始化...");
        Reflections f = new Reflections("com.xxx.xxx.entity");
        Set<Class<?>> classSet = f.getTypesAnnotatedWith(Document.class);
        for (Class<?> clazz : classSet) {
            IndexOperations indexOperations = restTemplate.indexOps(clazz);
            if (!indexOperations.exists()) {
                indexOperations.create();
                log.info(String.format("[elastic]索引%s数据结构创建成功", clazz.getSimpleName()));
            } else {
                log.info(String.format("[elastic]索引%s数据结构更新成功", clazz.getSimpleName()));
            }
            indexOperations.putMapping(indexOperations.createMapping(clazz));
        }
        log.info("[elastic]索引初始化完毕");
    }
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值