Elasticsearch-6.4.2 在 Java中的簡單連線
阿新 • • 發佈:2018-11-19
Elasticsearch版本為:Elasticsearch-6.4.2
1、主要應用包檔案:
<!-- Elasticsearch核心依賴包 --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>6.4.2</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>6.4.2</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>6.4.2</version> </dependency>
2、Windows 中啟動Elasticsearch服務
3、簡單程式碼連線,CRUD操作:
package com.allen.elasticsearch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.json.JSONObject; import java.io.IOException; import java.net.InetAddress; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.transport.client.PreBuiltTransportClient; public class ElasticsearchTest_1 { private Logger logger = LoggerFactory.getLogger(ElasticsearchTest_1.class); public final static String HOST="127.0.0.1"; //http請求的埠是9200,客戶端是9300 public final static int PORT = 9300; public final static String CLUSTERNAME = "elasticsearch"; public static TransportClient getConnection() throws Exception { Settings settings = Settings.builder() .put("client.transport.sniff", true) //增加嗅探機制,找到ES叢集 .put("cluster.name", CLUSTERNAME) // 設定叢集名稱 .put("thread_pool.search.size", 20)// 增加執行緒池個數,暫時設為20 .build(); // 建立client TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT)); return client; } /* * 新增 * 索引和型別是必需的,而id部分是可選的。如果不指定ID,ElasticSearch會為我們生成一個ID。 */ public void add() throws Exception{ try { XContentBuilder content = XContentFactory.jsonBuilder().startObject() .field("name","daniel") .field("age",20) .field("job","coder") .endObject(); String index = "data"; // 索引值 String type ="person"; // 型別 String id="1"; // id值 TransportClient client = this.getConnection(); IndexResponse iresp = client.prepareIndex(index, type,id).setSource(content).get(); client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 新增索引:傳入json字串 * id 自動建立 * * */ public void addJsonstr() throws Exception{ String jsonstr = "{\"userName\":\"Tom\",\"date\":\"2018-11-7\",\"msg\":\"where are you\"}"; TransportClient client = this.getConnection(); IndexResponse iresp = client.prepareIndex("chat", "msg").setSource(jsonstr,XContentType.JSON).get(); client.close(); System.err.println(iresp.getIndex()); System.err.println(iresp.getId()); System.out.println(iresp.status()); } /* * 新增索引:傳入json * * */ public void addJSON() throws Exception{ JSONObject json = new JSONObject(); json.put("userName", "allen"); json.put("date", new Date().toString()); json.put("msg", "hello allen"); TransportClient client = this.getConnection(); IndexResponse iresp = client.prepareIndex("chat", "msg","3").setSource(json,XContentType.JSON).get(); client.close(); System.err.println(iresp.getIndex()); System.err.println(iresp.getId()); System.out.println(iresp.status()); } /* * 建立索引-傳入Map物件 * * */ public void addMap() throws Exception{ Map<String, Object> map = new HashMap<String,Object>(); map.put("userName", "Daniel"); map.put("sendDate", new Date()); map.put("msg", "hello Daniel"); TransportClient client = this.getConnection(); IndexResponse response = client.prepareIndex("momo", "msg","1").setSource(map).get(); logger.info("map索引名稱:" + response.getIndex() + "\n map型別:" + response.getType() + "\n map文件ID:" + response.getId() + "\n當前例項map狀態:" + response.status()); } /* * 獲取資料 */ public void get(String index,String type,String id) throws Exception{ TransportClient client = this.getConnection(); GetResponse result = client.prepareGet(index,type,id).get(); System.out.println(result.getSourceAsString()); System.out.println(result.getType()); System.out.println(result.getVersion()); System.err.println(result.getIndex()); System.err.println(result.getId()); client.close(); } /* * 更新 */ public void update() throws Exception{ XContentBuilder content = XContentFactory.jsonBuilder().startObject(); content.field("age",22); content.field("job","boss"); content.endObject(); UpdateRequest request = new UpdateRequest("data","person","1"); request.doc(content); TransportClient client = this.getConnection(); UpdateResponse resp = client.update(request).get(); client.close(); } /* * 刪除 */ public void delete() throws Exception{ TransportClient client = this.getConnection(); DeleteResponse response = client.prepareDelete("data","person","1").get(); client.close(); System.out.println(response.getResult()); } /* * 關閉 */ public static void closeConnect(TransportClient client){ if(null !=client){ client.close(); } } public static void main(String[] args) throws Exception { /*TransportClient client = getConnection(); System.out.println(client.toString()); System.out.println(client.nodeName());*/ ElasticsearchTest_1 t = new ElasticsearchTest_1(); // t.add(); // t.get(); // t.update(); // t.get(); // t.delete(); // t.get("data","person","1"); // t.addJsonstr(); // t.get("chat", "msg","5jbh7GYB_P4tFfCC1ruQ"); // t.get("chat", "msg","5zbl7GYB_P4tFfCCpLt1"); // t.addJSON(); t.get("chat", "msg","3"); // t.addMap(); // t.get("momo", "msg","1"); } }