@Test
public void test2() throws IOException {
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
XContentBuilder doContentBuilder=XContentFactory.jsonBuilder()
.startObject()
.field("id", "1")
.field("title", "java设计模式之装饰模式")
.field("content", "在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能")
.field("postdate", "2018-05-20")
.field("url", "https://www.cnblogs.com/chenyuanbo/")
.endObject();
IndexResponse response = client.prepareIndex("index1","blog","10")
.setSource(doContentBuilder).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
System.out.println(response.status());
}
@Test
public void test3() throws UnknownHostException {
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
DeleteResponse response = client.prepareDelete("index1","blog","10").get();
System.out.println(response.status());
}
@Test
public void test4() throws IOException, InterruptedException, ExecutionException {
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
UpdateRequest request = new UpdateRequest();
request.index("index1")
.type("blog")
.id("10")
.doc(
XContentFactory.jsonBuilder()
.startObject()
.field("title", "单例设计模式")
.endObject()
);
UpdateResponse response= client.update(request).get();
System.out.println(response.status());
}
- upsert修改用法:修改文章存在,执行修改,不存在则执行插入
@Test
public void test5() throws IOException, InterruptedException, ExecutionException {
Settings settings = Settings.builder().put("cluster.name", "my-application").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.94"), 9300));
IndexRequest request1 = new IndexRequest("index1","blog","8").source(
XContentFactory.jsonBuilder()
.startObject()
.field("id", "2")
.field("title", "工厂模式")
.field("content", "静态工厂,实例工厂")
.field("postdate", "2018-05-20")
.field("url", "https://www.cnblogs.com/chenyuanbo/")
.endObject()
);
UpdateRequest request2 = new UpdateRequest("index1","blog","8").doc(
XContentFactory.jsonBuilder().startObject()
.field("title", "设计模式")
.endObject()
).upsert(request1);
UpdateResponse response = client.update(request2).get();
System.out.println(response.status());
}