动态设置ElasticSearch中@Document的index值

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值