elasticsearch 插入數據


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();
                    }
            }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM