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