[英]Creating Indices name Dynamically in Elasticsearch using Spring-Data 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));
我沒有使用我班級的映射和設置,因為我需要它是動態的。
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 { //... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.