第四节 在Java应用中访问ElasticSearch
4.1在Java应用中实现查询文档
pom中加入ElasticSearch6.2.4的依赖:
org.elasticsearch.client
transport
6.2.4
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.2
1.8
1.8
UTF-8
4.2 在Java应用中实现添加文档
"{" +
""id":"1"," +
""title":"Java设计模式之装饰模式"," +
""content":"在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。"," +
""postdate":"2018-05-20 14:38:00"," +
""url":"csdn.net/79239072"" +
"}"
XContentBuilder doc1 = XContentFactory.jsonBuilder()
.startObject()
.field(“id”,”3″)
.field(“title”,”Java设计模式之单例模式”)
.field(“content”,”枚举单例模式可以防反射。”)
.field(“postdate”,”2018-02-03″)
.field(“url”,”csdn.net/79247746″)
.endObject();
IndexResponse response = client.prepareIndex("index1", "blog", null)
.setSource(doc1)
.get();
System.out.println(response.status());
4.3在Java应用中实现删除文档
DeleteResponse response=client.prepareDelete(“index1″,”blog”,”SzYJjWMBjSAutsuLRP_P”).get();
//删除成功返回OK,否则返回NOT_FOUND
System.out.println(response.status());
4.4在Java应用中实现更新文档
UpdateRequest request=new UpdateRequest();
request.index(“index1”)
.type(“blog”)
.id(“2”)
.doc(
XContentFactory.jsonBuilder().startObject()
.field(“title”,”单例模式解读”)
.endObject()
);
UpdateResponse response=client.update(request).get();
//更新成服务器托管网功返回OK,否则返回NOT_FOUND
System.out.println(response.status());
upsert方式:
IndexRequest request1 =new IndexRequest(“index1″,”blog”,”3″)
.source(
XContentFactory.jsonBuilder().startObject()
.field(“id”,”3″)
.field(“title”,”装饰模式”)
.field(“content”,”动态地扩展一个对象的功能”)
.field(“postdate”,”2018-05-23″)
.field(“url”,”csdn.net/79239072″)
.endObject()
);
UpdateRequest request2=new UpdateRequest(“index1″,”blog”,”3″)
.doc(
XCont服务器托管网entFactory.jsonBuilder().startObject()
.field(“title”,”装饰模式解读”)
.endObject()
).upsert(request1);
UpdateResponse response=client.update(request2).get();
//upsert操作成功返回OK,否则返回NOT_FOUND
System.out.println(response.status());
4.5在Java应用中实现批量操作
MultiGetResponse mgResponse = client.prepareMultiGet()
.add(“index1″,”blog”,”3″,”2″)
.add(“lib3″,”user”,”1″,”2″,”3″)
.get();
for(MultiGetItemResponse response:mgResponse){
GetResponse rp=response.getResponse();
if(rp!=null && rp.isExists()){
System.out.println(rp.getSourceAsString());
}
}
bulk:
BulkRequestBuilder bulkRequest = client.prepareBulk();
bulkRequest.add(client.prepareIndex(“lib2”, “books”, “4”)
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field(“title”, “python”)
.field(“price”, 68)
.endObject()
)
);
bulkRequest.add(client.prepareIndex(“lib2”, “books”, “5”)
.setSource(XContentFactory.jsonBuilder()
.startObject()
.field(“title”, “VR”)
.field(“price”, 38)
.endObject()
)
);
//批量执行
BulkResponse bulkResponse = bulkRequest.get();
System.out.println(bulkResponse.status());
if (bulkResponse.hasFailures()) {
System.out.println("存在失败操作");
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
前言 你可能已经听过很多遍这个不算秘密的秘密了–Kubernetes Secrets 不是加密的!Secret 的值是存储在 etcd 中的 base64 encoded(编码) 字符串。这意味着,任何可以访问你的集群的人,都可以轻松解码你的敏感数据。任何人…