1、單條插入(推薦設定主鍵id防止重復)
public static String addIndex(String index,String type,HashMap<String, Object> hashMap){
hashMap.put("id", "3"); //這里如果不指定id的話elasticsearch會自動創建主鍵id,
hashMap.put("title","雙宿雙飛從");
hashMap.put("describe", "測試123");
hashMap.put("author", "測試doc");
TransportClient client=EsClientPool.getInstance().getClient();
try {
IndexResponse response = client.prepareIndex(index, type,hashMap.get("id").toString())
.setSource(hashMap).execute().actionGet();
System.out.println(response.getId());
return response.getId(); //返回主鍵
} catch (Exception e) {
// TODO: handle exception
return null;
}finally{
client.close();//關閉連接
}
}
2、批量插入
public static void addAllIndex(String index,String type,HashMap<String, Object> hashMap){
hashMap.put("title","雙宿雙飛從");
hashMap.put("describe", "測試123");
hashMap.put("author", "測試doc");
TransportClient client=EsClientPool.getInstance().getClient();
try {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (int i = 0; i < 10000; i++) {
bulkRequest.add(client.prepareIndex(index, type).setSource(hashMap));
// 每1000條提交一次
if (i % 10000 == 0) {
bulkRequest.execute().actionGet();
}
}
} catch (Exception e) {
}finally{
client.close();
}
}