图灵架构师第4期学习-百度网盘下载-java文档中心,金山云-文档中心-Java API
【微信642620018,获取全套课程】
Transport Client
1.创建transport client。
// on startup
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
//Add transport addresses and do something with the client...
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));
// on shutdown
client.close();
2.添加参数,client.transport.sniff=true(默认是false,表示不开启集群嗅探功能)。
Settings settings = Settings.builder()
.put("client.transport.sniff", true).build();
TransportClient client = new PreBuiltTransportClient(settings);
备注:这仅是举例说明添加参数的方式,一般client.transport.sniff不需要修改,更多的细节请参考:ES5.6-transport-client。
Elasticsearch6.8.x
强烈建议使用Rest Client,使用Transport Client客户端连接不同版本的elasticsearch实例时,会存在兼容性问题,官方在elasticsearch8.0中不再支持Transport Client
Transport Client
1.创建transport client。
// on startup
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("host1"), 9300))
.addTransportAddress(new TransportAddress(InetAddress.getByName("host2"), 9300));
// on shutdown
client.close();
2.添加参数:client.transport.sniff=true(默认是false,表示不开启集群嗅探功能)。
Settings settings = Settings.builder()
.put("client.transport.sniff", true).build();
TransportClient client = new PreBuiltTransportClient(settings);
备注:这仅是举例说明添加参数的方式,一般client.transport.sniff不需要修改,更多的细节请参考,ES6.8-transport-client
Java High Level REST Client
依赖JDK版本1.8+,pom依赖需要添加。
org.elasticsearch.client
elasticsearch-rest-high-level-client
6.8.4
举个index,get,delete,update的简单例子:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("{elasticsearch集群地址}", 9200, "http")));
//index
Map jsonMap = new HashMap<>();
jsonMap.put("{filed1}", "{value1}");
jsonMap.put("{field2}", "{value2}");
IndexRequest indexRequest = new IndexRequest("{index}", "{type}", "{docid}")
.source(jsonMap);
IndexResponse indexResponse = client.index(indexRequest , RequestOptions.DEFAULT);
//get
GetRequest getRequest = new GetRequest(
"{index}",
"{type}",
"{docid}");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//delete
DeleteRequest deleteRequest = new DeleteRequest(
"{index}",
"{type}",
"{docid}");
DeleteResponse deleteResponse = client.delete(
deleteRequest, RequestOptions.DEFAULT);
//update
UpdateRequest updateRequest = new UpdateRequest("{index}", "{type}", "{docid}")
.doc(jsonMap);
UpdateResponse updateResponse = client.update(
updateRequest, RequestOptions.DEFAULT);
client.close();