使用Spring-Data Elasticsearch在Elasticsearch中动态创建索引名称
我有一个用例,需要在Elasticsearch中每月创建索引。 我们的想法是在月度基础上创建指数,以便它们易于维护,并且可以在过期时删除。为此我要使用春季批次并且每月工作将创建每月基数的指数对于Elasticsearch -Java集成我使用了Spring-Data Elasticsearch实现。 我现在面临的问题是,我无法弄清楚如何使用Entity对象为索引和映射提供动态名称。 我目前的实施完成时要记住单一索引。 请找到以下用于创建索引的代码
elasticsearchTemplate.createIndex(SingleChat.class); elasticsearchTemplate.putMapping(SingleChat.class); elasticsearchTemplate.refresh(SingleChat.class, true);
而SingleChat是我的实体类
@Document(indexName="singlemsgtemp_#{jobParameters['MONTH']}",type="singlechat") public class SingleChat { @org.springframework.data.annotation.Id String Id; @Field(type = FieldType.String) String conservationId; @Field(type = FieldType.String) String from; @Field(type = FieldType.String) String to; @Field(type = FieldType.String) String msgContent; @Field(type = FieldType.String) String sessionId; @Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store = true, format = DateFormat.date_hour_minute_second_millis) Date postedDate; @Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store = true, format = DateFormat.date_hour_minute_second_millis) Date expireDate; }
但这不符合预期。 我也在尝试其他一些东西。 但我愿意接受建议。 也可以随意评论我目前的方法,它是否有效。 如果需要更多详细信息,请与我们联系。
我在我的应用程序上做的是我使用ElasticSearchTemplate创建我的动态索引名称然后我将别名指向我创建的新索引,然后删除旧索引。
esTemplate.createIndex(newIndexName, loadfromFromFile(settingsFileName)); esTemplate.putMapping(newIndexName, "MYTYPE", loadfromFromFile(mappingFileName));
我没有使用我class级的映射和设置,因为我需要它是动态的。
protected String loadFromFile(String fileName) throws IllegalStateException { StringBuilder buffer = new StringBuilder(2048); try { InputStream is = getClass().getResourceAsStream(fileName); LineNumberReader reader = new LineNumberReader(new InputStreamReader(is)); while (reader.ready()) { buffer.append(reader.readLine()); buffer.append(' '); } } catch (Exception e) { throw new IllegalStateException("couldn't load file " + fileName, e); } return buffer.toString(); }
我在我的项目中正在做什么,我们在更改时将索引名称和类型名称存储在DB中。
现在我以这种方式获取索引和动态类型:
第一解决方案
-
1)在配置文件中,创建一个Bean,为someProperty返回一个值。 这里我从DB或属性文件中注入somePropertyValue和@Value注释: –
@Value("${config.somePropertyValue}") private String somePropertyValue; @Bean public String somePropertyValue(){ return somePropertyValue; }
-
2)在此之后,可以将somePropertyValue注入到@Document注释中,如下所示: –
@Document(index = "#{@somePropertyValue}") public class Foobar { //... }
二解决方案
-
1)在bean中创建getter setter: –
@Component public class config{ @Value("${config.somePropertyValue}") private String somePropertyValue; public String getSomePropertyValue() { return somePropertyValue; } public void setSomePropertyValue(String somePropertyValue) { this.somePropertyValue = somePropertyValue; } }
-
2)在此之后,可以将somePropertyValue注入到@Document注释中,如下所示: –
@Document(index = "#{config.somePropertyValue}") public class Foobar { //... }