新建項目:java
pom.xml文件引入依賴json
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>6.1.2</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>
private static final String host = "192.168.15.38"; private static final int port = 9300; private static TransportClient client = null; public static TransportClient cilentFactory() { client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddress(new TransportAddress(new InetSocketAddress(host, port))); return client; } public static void close() { if (client != null) { client.close(); } }
IndexResponse response = client.prepareIndex("user", "basic_info","1").setSource(jsonObject.toString(), XContentType.JSON).get(); System.out.println("索引:" + response.getIndex()); System.out.println("類型:" + response.getType()); System.out.println("id:" + response.getId()); System.out.println("狀態" + response.status());
GetResponse response1 = client.prepareGet("user", "basic_info","1").get(); System.out.println(response1.getSourceAsString());
JsonObject jsonObject2 = new JsonObject(); jsonObject2.addProperty("name", "張三1"); jsonObject2.addProperty("age", 21); jsonObject2.addProperty("address", "山東威海1"); jsonObject2.addProperty("email", "zhagnsan_smile@163.com1"); //修改文檔 UpdateResponse updateResponse = client.prepareUpdate("user", "basic_info","1").setDoc(jsonObject2.toString(),XContentType.JSON).get(); System.out.println(updateResponse.getId());
DeleteResponse deleteResponse = client.prepareDelete("user", "basic_info","1").get(); System.out.println(deleteResponse.status());