需求说明
elasticsearch索引问题,致使数据查询时不能根据一个索引完成。Es索引本来式在配置文件中读取,故障发生后,约定好:随着时间的推移自动生成Es索引。
以下为代码实现,分别生成:本月和上月的索引;截至到本月所有的索引。
/**
* @author: localhost
* @program: kq-itmb-relly
* @description: 本月和上月的EsIndex
* @create: 2019-01-24 16:20
**/
public class LastEsIndex {
public static List<String> getLastEsIndex(Date date) throws ParseException {
List<String> strList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String str = sdf.format(date);
String newEsIndex;
String[] split = str.split("-");
String newCurMonth;
String lastMonth;
if (split[0].equals("2018")) {
newCurMonth = "vehilcepasshk";
} else {
newCurMonth = "vehilcepasshk-" + split[0] + "." + split[1];
}
//上月
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(str));
c.add(Calendar.MONTH, -1);
String s = sdf.format(c.getTime());
String[] split1 = s.split("-");
if (split1[0].equals("2018")) {
lastMonth = "vehilcepasshk";
} else {
lastMonth = "vehilcepasshk-" + split1[0] + "." + split1[1];
}
strList.add(lastMonth);
strList.add(newCurMonth);
return strList;
}
}
/**
* @author: localhost
* @program: kq-itmb-relly
* @description: 截至到本月之前所有的es索引
* @create: 2019-01-24 16:06
**/
public class AllEsIndex {
public static String getAllEsindex(Date date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String time = sdf.format(date);
String newEsIndex;
newEsIndex = "vehilcepasshk,";
List<String> list = getMonthBetween("2019-01-01", time);
for (String str : list) {
String[] split = str.split("-");
String newStr = "vehilcepasshk-" + split[0] + "." + split[1] + ",";
newEsIndex += newStr;
}
String ss = newEsIndex.substring(0, newEsIndex.length() - 1);
return ss;
}
//获取指定日期之间的所有年月
private static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException {
ArrayList<String> result = new ArrayList<String>();
//格式化为年月
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
return result;
}
}
测试类
/**
* @author: localhost
* @program: kq-itmb-relly
* @description: 获取这个月和上月生成的索引
* @create: 2019-01-23 18:12
**/
public class TimeTest {
public static void main(String[] args) throws ParseException {
List<String> lastEsIndex = LastEsIndex.getLastEsIndex(new Date());
//******************本周以及上周***************
System.out.println(lastEsIndex.get(0));
System.out.println(lastEsIndex.get(1));
//******************截至到目前***************
String allEsindex = AllEsIndex.getAllEsindex(new Date());
System.out.println(allEsindex);
}
}
网友评论