Spring Data Elasticsearch动态索引配置

Spring Data Elasticsearch动态索引配置

  • application.yml配置
  • JavaConfig定义
  • 实体类索引配置

spring-data-elasticsearch 支持@Document(indexName = {javaConfig.property})方式配置索引名称,下面看具体配置:

application.yml配置

自定义属性index-name

spring:
  data:
    elasticsearch:
      cluster-name: myescluster
      cluster-nodes: ip1:9300, ip2:9300, ip3:9300
      index-name: test

JavaConfig定义

@Data为lombok提供的注解

@Component
@Data
public class AppConfig {

    @Value("${spring.data.elasticsearch.index-name}")
    private String indexName;
}

实体类索引配置

/**
 * MyObject实体
 *
 * @author Java猿人一枚
 * @since 2019-03-26
 */
@Data
@Document(indexName = "#{appConfig.indexName}", type = "myObject")
public class MyObject {

    @Id
    @Field(index = false, store = true, type = FieldType.Keyword)
    private String tid;

    @Field(index = true, store = true, analyzer = "ik", searchAnalyzer = "ik", type = FieldType.Text)
    private String title;

    @Field(index = true, store = true, analyzer = "ik", searchAnalyzer = "ik", type = FieldType.Text)
    private String content;

    @Field(index = false, store = true, type = FieldType.Date, format = DateFormat.custom,pattern = "yyyy-MM-dd HH:mm:ss")
    private Date time;

}

如上所述,即完成了配置文件配置索引名称,实体索引名称动态传入配置的功能
感兴趣的同学动手试试吧!

你可能感兴趣的:(spring,data,elasticsearch)