1.在配置文件里设置indexName(只能设置一个indexName)
创建配置Bean:
@Component("esAttribute")
// 指定配置文件
@PropertySource("classpath:application.properties")
public class EsAttribute {
@Value("${index.name}")
private String indexName;
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
}
在application.properties中添加:
index.name=tomcat1-*
在ElasticSearch返回的类型中使用:
@Data
@NoArgsConstructor
@Accessors(chain = true)
@Document(indexName = "#{@esAttribute.indexName}", shards = 1, replicas = 0,createIndex = true)
public class AppLogBean implements Serializable {
private static final long serialVersionUID = -729624360020627702L;
@Id
private String id;
@Field(type = FieldType.Keyword)
private String customer_time;
}
在操作过程中可能会报这个错误:java.lang.IllegalArgumentException: Could not resolve placeholder ‘index.name’ in value "${index.name}
原因可能是使用@Value的类上未指定配置文件:@PropertySource("classpath:application.properties")
也可能是你的配置文件是yml类型,而该注解只支持properties文件引入,并不支持yml,至于如何让其可以加载yml文件,自行搜索。
2.在代码中设置indexName(可以根据条件设置不同的indexName)
创建配置Bean:
@Component("esAttribute")
public class EsAttribute {
private String indexName;
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
}
在你需要的地方设置indexName:
@Autowired
private EsAttribute esAttribute;
// 动态设置索引名称
esAttribute.setIndexName("tomcat1-*");
logger.info("索引名称indexName:" + esAttribute.getIndexName());
在ElasticSearch返回的类型中使用:
@Data
@NoArgsConstructor
@Accessors(chain = true)
@Document(indexName = "#{@esAttribute.indexName}", shards = 1, replicas = 0,createIndex = true)
public class AppLogBean implements Serializable {
private static final long serialVersionUID = -729624360020627702L;
@Id
private String id;
@Field(type = FieldType.Keyword)
private String customer_time;
}
参考文章:https://www.jianshu.com/p/882b91652400
https://blog.csdn.net/qq_35188937/article/details/81778484