31.Elasticsearch批量匯入本地Json檔案Java實現(ES檔案同步)
阿新 • • 發佈:2019-01-09
題記
產品開發需要,我們需要將網際網路採集的資料儲存到ES中,以實現資料的全文檢索。
網際網路採集的資料,往往格式雜亂,需要先進行資料清洗操作。
而ES支援的入庫格式,json格式資料會相對方便些。
本文主要介紹,如何將格式化的Json檔案批量插入到ES中。
1、需提前做的工作
1)設計好索引以及Mapping;
Mapping的目的主要是——設定欄位名稱、欄位型別,哪些欄位需要進行全文檢索等。
- 1
2)Java程式中封裝好類,和Mapping設定的欄位一一對應。
2、批量匯入步驟分解
步驟1:本地檔案格式化,統一為Json格式。
一個待匯入的資料串,存成一個Json檔案。
步驟2:放置在統一./data路徑下。 目錄結構如下示意:
./data
a_01.json
a_02.json
a_03.json
...
a_100.json
步驟3:迴圈遍歷./data檔案獲取包含絕對路徑的檔案全名,存入linkedlist中。
步驟4:遍歷linkedlist的每個路徑,獲取Json資訊。
步驟5:使用fastjson解析Json,解析成對應設計好的類個各個匹配欄位。
步驟6:藉助bulk**批量曹操API介面,完成本地檔案的匯入。
3、核心介面實現
/*
**@brief:遍歷Json,批量插入ES
**@param:空
**@return:空
*/
private static void insertBulkIndex() throws Exception {
//Json檔案的儲存
final String JSONFILEINPUT = ESConfig.es_json_path;
logger.info("path = " + JSONFILEINPUT);
LinkedList<String> curJsonList = FileProcess.getJsonFilePath(JSONFILEINPUT);
logger.info("size = " + curJsonList.size());
for (int i = 0 ; i < curJsonList.size(); ++i){
//System.out.println(" i = " + i + " " + curJsonList.get(i));
String curJsonPath = curJsonList.get(i);
ImageInfo curImageInfo = JsonParse.GetImageJson(curJsonPath);
//JsonParse.printImageJson(curImageInfo);
if (curImageInfo == null){
continue;
}
//遍歷插入操作
InsertIndex (curImageInfo);
}
}
/*
**@brief:單條Json插入ES(藉助了Jest封裝後的API)
**@param:空
**@return:空
*/
private static void InsertIndex(AgeInfo ageInfo) throws Exception {
JestClient jestClient = JestExa.getJestClient();
JsonParse.PrintImageJson( ageInfo );
Bulk bulk = new Bulk.Builder()
.defaultIndex("age_index")
.defaultType("age_type")
.addAction(Arrays.asList(
new Index.Builder( ageInfo ).build()
)).build();
JestResult result = jestClient.execute(bulk);
if (result.isSucceeded()){
System.out.println("insert success!");
}else{
System.out.println("insert failed");
}
}
最終實現效果為:
java -jar bulk_insert.jar ./data/
即可實現./data下的所有json迴圈遍歷匯入ES。
4、使用技術
1)檔案遍歷
2)Json解析
3)ES批量插入操作
5、遇到的坑
程式匯出Jar包時候,生成jar包報錯。
由於藉助了Jest的原始碼工程,該工程是由Maven生成的。
生成jar包的時候,會一直提示:
“Java.long.ClassNotFoundException"
初步定位原因:是maven導致,然後了pom.xml,錯誤依舊。
最終解決方案:重建工程,將程式碼和依賴的jar包重新匯入即可。
後記
死磕ES,有問題歡迎大家提問探討!