0.引言
在springboot整合spring data elasticsearch项目中,当索引数量较多,mapping结构较为复杂时,我们常常希望启动项目时能够自动创建索引及mapping,这样就不用再到各个环境中创建索引了
所以今天咱们就来看看如何自动创建索引
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
创建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;
}
利用createIndex属性实现
如股票使用的是spring data elasticsearch包,其@Document注解中包含了一个createIndex属性,默认为true,也就是默认开启了自动创建索引的,想要关闭也可通过设置为false来实现。
利用反射实现
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]索引初始化完毕");
}
}