1. ES 启动监听两个端口: 9200与9300的区别
9300是Tcp协议端口:通过tcp协议通讯,ES集群之间是通过9300进行通讯,java客户端(TransportClient)的方式是也是以tcp协议在9300 端口上与集群进行通信。
9200是Http协议端口:主要用于外部通讯,外部使用RESTful接口进行访问。 如下图:url地址上输入对应的RESTful接口 就可以访问。
2. 高级客户端连接ES集群
2.1介绍:ES提供了两个JAVA REST client 版本
- Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。(PS:学过WebService的话,对编排与反编排这个概念应该不陌生。可以理解为对请求参数的封装,以及对响应结果的解析)
- Java High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供很多API,并负责请求的编排与响应的反编排。( PS:就好比是,一个是传自己拼接好的字符串,并且自己解析返回的结果;而另一个是传对象,返回的结果也已经封装好了,直接是对象,更加规范了参数的名称以及格式,更加面对对象一点 )
( PS:所谓低级与高级,我觉得一个很形象的比喻是,面向过程编程与面向对象编程 )
在 Elasticsearch 7.0 中不建议使用TransportClient,并且在8.0中会完全删除TransportClient。因此,官方更建议我们用Java High Level REST Client,它执行HTTP请求,而不是序列号的Java请求。既然如此,这里就直接用高级了。
2.2 Maven仓库配置
高级客户端要与Elasticsearch集群进行通信,主版本号需要一致,次版本号不必相同。
本案例,es 使用6.8.0版本,而高级客户端使用6.6.2是可以的。例如:6.0客户端能够与任何6.x Elasticsearch节点通信,而6.1客户端肯定能 够与6.1,6.2和任何后来的6.x版本进行通 信,但与旧版本的 Elasticsearch节点通信时可能会存在不兼容的问题,例如6.1和6.0之间, 可能6.1客户端支持elasticsearch 6.0还没出来的API。
1 <dependency> 2 <groupId>org.elasticsearch.client</groupId> 3 <artifactId>elasticsearch-rest-high-level-client</artifactId> 4 <version>6.6.2</version> 5 </dependency>
连接到es集群 RestHighLevelClient实例需要低级客户端构建器来构建,
如下所示: RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.20.210", 9200, "http"))
);
高级客户端将在内部创建低级客户端,用来执行基于提供的构建器的请求,并
管理其生命周期。
当不再需要时,需要关闭高级客户端实例,以便它所使用的所有资源以及底层 的http客户端实例及其线程得到正确释放。可以通过close方法来完成,该方法将关闭内部的RestClient实例。
client.close();
/* 使用高级客户端连接ES集群 */ public class ElasticSearchClient { public static void main(String[] args){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost ("localhost", 9200, "http") ) ); GetIndexRequest request = new GetIndexRequest(); request.indices("test"); boolean exists = false; try { exists = client.indices().exists(request, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace (); } if(exists){ System.out.println("test索引库存在"); }else{ System.out.println("test索引库不存在"); } //关闭高级客户端实例,以便它所使用的所有资源以及底层 的http客户端实例及其线程得到正确释放 try { client.close(); } catch (IOException e) { e.printStackTrace (); } } }
2.3 创建索引 四种方式
索引index(四种json,map,XContentBuilder,object)
IndexResponse indexResponse = client.index(indexRequest,RequestOptions.DEFAULT);
1 /** 2 * index api 3 * @throws IOException 4 */ 5 @Test 6 public void test3() throws IOException { 7 XContentBuilder builder = XContentFactory.jsonBuilder(); 8 builder.startObject(); 9 { 10 builder.field("user", "kimchy"); 11 builder.timeField("postDate", new Date()); 12 builder.field("message", "trying out Elasticsearch"); 13 } 14 builder.endObject(); 15 IndexRequest indexRequest = new IndexRequest("posts", "doc", "1") 16 .source(builder); 17 18 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); 19 System.out.println(indexResponse.getId()); 20 client.close(); 21 } 22 23 /** 24 * index api 25 * @throws IOException 26 */ 27 @Test 28 public void test4() throws IOException { 29 IndexRequest indexRequest = new IndexRequest("posts", "doc", "1") 30 .source("user", "kimchy", 31 "postDate", new Date(), 32 "message", "trying out Elasticsearch"); 33 34 IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); 35 System.out.println(indexResponse.getId()); 36 client.close(); 37 }
运行结果:如图从head插件中可以看书创建了‘posts’索引,和四个文档。
2.4 索引查询
官网代码:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.8/java-rest-high-document-get.html
@Test public void test5() throws IOException { GetRequest getRequest = new GetRequest( "posts", "doc", "1"); GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); System.out.println(getResponse.getSource()); client.close(); }
运行结果:
{postDate=2019-06-14T09:15:05.372Z, message=trying out Elasticsearch, user=kimchy}
2.5 索引判断exist 索引更新update 索引删除delete 批量操作bulk 多条数据查询Multi Get
/** * exist api * @throws IOException */ @Test public void test6() throws IOException { GetRequest getRequest = new GetRequest( "posts", "doc", "1"); getRequest.fetchSourceContext(new FetchSourceContext (false)); getRequest.storedFields("_none_"); boolean exists = client.exists(getRequest, RequestOptions.DEFAULT); if(exists){ System.out.println("数据存在"); }else{ System.out.println("数据不存在"); } client.close(); } /** * update api * @throws IOException */ @Test public void test7() throws IOException { UpdateRequest request = new UpdateRequest( "posts", "doc", "1"); String jsonString = "{" + ""updated":"2017-01-01"," + ""reason":"daily update"" + "}"; request.doc(jsonString, XContentType.JSON); UpdateResponse updateResponse = client.update( request, RequestOptions.DEFAULT); client.close(); } /** * delete api * @throws IOException */ @Test public void test8() throws IOException { DeleteRequest request = new DeleteRequest( "posts", "doc", "1"); DeleteResponse deleteResponse = client.delete( request, RequestOptions.DEFAULT); client.close(); } /** * bulk api * @throws IOException */ @Test public void test9() throws IOException { BulkRequest request = new BulkRequest(); request.add(new DeleteRequest("posts", "doc", "3")); request.add(new UpdateRequest("posts", "doc", "2") .doc(XContentType.JSON,"other", "test")); request.add(new IndexRequest("posts", "doc", "4") .source(XContentType.JSON,"field", "baz")); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); if (bulkResponse.hasFailures()) { for (BulkItemResponse bulkItemResponse : bulkResponse) { if (bulkItemResponse.isFailed()) { BulkItemResponse.Failure failure = bulkItemResponse.getFailure(); System.out.println(failure.getMessage()); } } } client.close(); } /** * multi get api * @throws IOException */ @Test public void test10() throws IOException { MultiGetRequest request = new MultiGetRequest(); request.add(new MultiGetRequest.Item( "test", "user", "2")); request.add(new MultiGetRequest.Item("test", "user", "4")); MultiGetResponse responses = client.mget(request, RequestOptions.DEFAULT); for (MultiGetItemResponse itemResponse : responses) { GetResponse response = itemResponse.getResponse(); if (response.isExists()) { String json = response.getSourceAsString(); System.out.println(json); } } client.close(); }