通過Java程序連接Elasticsearch

9200端口是用於Http協議訪問的,如果通過客戶端訪問需要通過9300端口才可以訪問

初始化的兩種方式:

1.

RestHighLevelClient client = new RestHighLevelClient(

        RestClient.builder(

                new HttpHost("localhost", 9200, "http"),

                new HttpHost("localhost", 9201, "http")));

2.

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(

                 new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));

一 創建索引

IndexResponse response = client.prepareIndex("msg","tweet", "1").setSource(XContentFactory.jsonBuilder().startObject().field("userName", "張三").field("sendDate", new Date()).field("msg", "你好李四").endObject()).get();

 

二 向索引庫中添加json字符串

String jsonStr = "{" +

                "\"userName\":\"張三\"," +

                "\"sendDate\":\"2017-11-30\"," +

                "\"msg\":\"你好李四\"" +

            "}";
IndexResponse response = client.prepareIndex("weixin", "tweet").setSource(jsonStr,XContentType.JSON).get();

 

三 從索引庫獲取數據

GetResponse getResponse = client.prepareGet("msg", "tweet", "1").get();

logger.info("索引庫的數據:" + getResponse.getSourceAsString());

 

四 更新索引庫數據

JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("userName", "王五");

        jsonObject.addProperty("sendDate", "2008-08-08");

        jsonObject.addProperty("msg","你好,張三,好久不見");

UpdateResponse updateResponse = client.prepareUpdate("msg", "tweet", "1").setDoc(jsonObject.toString(),XContentType.JSON).get();

 

五 刪除索引庫數據

DeleteResponse deleteResponse = client.prepareDelete("msg", "tweet", "1").get();

六 查看索引是否存在

Response response = restClient.performRequest("HEAD", index);

    boolean exist = response.getStatusLine().getReasonPhrase().equals("OK");

return exist;

 

七 刪除索引

Response response = restClient.performRequest("DELETE", indexName);

八 根據id查詢數據

GetResponse getResponse = client.prepareGet("index", "type", "id").get();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章