/**
* 创建模板
* 注:
* 1.读取templateFilePath目录下所有.json结尾的文件
* 2.模板名为文件名称
* 3.模板内容为文件内容
*
* @param templateFilePath 模板文件路径
*/
public static void createESTemplate(String templateFilePath) {
log.info("开始创建模板, 模板文件夹路径:" + templateFilePath);
try {
Client client = ElasticSearchManager.getClient();
// URL templateUri = ESTools.class.getClassLoader().getResource(templateFilePath);
File fileTemplateDir = new File(templateFilePath);
File[] templateFiles = fileTemplateDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
// 遍历文件夹下所有json文件
for (File file : templateFiles) {
if (file.exists() && !file.isDirectory()) {
try {
InputStream is = new FileInputStream(file);
String templateJson = IOUtils.toString(is, StandardCharsets.UTF_8);
JSONObject templateJsonObject = JSONObject.fromObject(templateJson);
String templateName = file.getName().substring(0, file.getName().lastIndexOf("."));
log.info("创建模板, 当前模板名称:" + templateName);
PutIndexTemplateRequest request = new PutIndexTemplateRequest(templateName);
request.source(templateJsonObject.toString());
request.create(true);// 只创建, 不覆盖
ActionFuture<PutIndexTemplateResponse> futer = client.admin().indices().putTemplate(request);
boolean res = futer.get().isAcknowledged();
log.info("创建模板结果:" + res);
} catch (Exception e) {
log.error("创建模板错误 ![当前模板名称]" + file.getName() + " [error]" + e.getMessage());
}
} else {
log.warn("文件不存在或文件为文件夹! file path:" + file.toPath());
}
}
} catch (Exception e) {
log.error("创建模板错误!error:" + e.getMessage());
}
}
模板json文件:
{
"order": 0,
"template": "test*",
"settings": {
"index": {
"number_of_replicas": "0",
"max_result_window": "50000",
"number_of_shards": "2"
}
},
"mappings": {
"test": {
"properties": {
"id": {
"index": "not_analyzed",
"type":"string"
},
"reportTime": {
"type": "long"
},
"contents": {
"index": "not_analyzed",
"type": "string"
},
"state": {
"type": "long"
},
"mqIp": {
"index": "not_analyzed",
"type": "string"
},
"type": {
"type": "long"
}
}
},
"aliases": {}
}