如果是 Spring Boot 项目,就不用添加第二个依赖了,因为 Spring Boot 的 Web 中默认已经加了这个依赖了,但是 Spring Boot 一般需要额外添加下面这个依赖,出现这个原因是由于从 JavaEE 过渡到 JakartaEE 时衍生出来的一些问题,这里我就不啰嗦了,咱们直接加依赖即可:
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchAsyncClient client = new ElasticsearchAsyncClient(transport);
1.
2.
3.
4.
5.
只有第三步和前面的不一样,其他都一样。
利用阻塞的 Java 客户端操作 Es 的时候会发生阻塞,也就是必须等到 Es 给出响应之后,代码才会继续执行;非阻塞的 Java 客户端则不会阻塞后面的代码执行,非阻塞的 Java 客户端一般通过回调函数处理请求的响应值。
有时候,我们可能还需要和 Es 之间建立 HTTPS 连接,那么需要在前面代码的基础之上,再套上一层 SSL,如下:
String fingerprint ="<certificate fingerprint>";
SSLContext sslContext = TransportUtils
.sslContextFromCaFingerprint(fingerprint);
BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
credsProv.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(login, password));
RestClient restClient = RestClient
.builder(new HttpHost(host, port,"https")).setHttpClientConfigCallback(hc -> hc
.setSSLContext(sslContext).setDefaultCredentialsProvider(credsProv)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
好了,关于建立连接,差不多就这些点。
4. 索引操作
Elasticsearch Java API Client 中最大的特色就是建造者模式+Lambda 表达式。例如,我想创建一个索引,方式如下:
@Test
public void test99() throws IOException {
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
CreateIndexResponse createIndexResponse = client.indices().create(
c ->
c.index("javaboy_books").settings(s ->
s.numberOfShards("3").numberOfReplicas("1")).mappings(m ->
m.properties("name", p -> p.text(f -> f.analyzer("ik_max_word"))).properties("birthday", p -> p.date(d -> d.format("yyyy-MM-dd")))).aliases("books_alias", f -> f.isWriteIndex(true)));
System.out.println("createResponse.acknowledged() = "+ createIndexResponse.acknowledged());
System.out.println("createResponse.index() = "+ createIndexResponse.index());
System.out.println("createResponse.shardsAcknowledged() = "+ createIndexResponse.shardsAcknowledged());}
PUT javaboy_books
{"settings":{"number_of_replicas":1,"number_of_shards":3},"mappings":{"properties":{"name":{"type":"text","analyzer":"ik_max_word"},"birthday":{"type":"date","format":"yyyy-MM-dd"}}},"aliases":{"xxxx":{}}}
@Test
public void test06() throws IOException {
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);//删除一个索引
DeleteIndexResponse delete= client.indices().delete(f ->
f.index("my-index"));
System.out.println("delete.acknowledged() = "+delete.acknowledged());}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
这个表示删除一个名为 my-index 的索引。
好了,关于索引的操作我就说这两点。
可能有的小伙伴会说,ElasticSearch 中创建索引可以配置很多参数你都没讲。在我看来,哪些很多参数其实跟这个 Java API 没有多大关系,只要你会写查询脚本,就自然懂得 Java API 中该调用哪个方法,退一万步讲,你会脚本,不懂 Java API 的方法,那么就像上面那样,直接把你的 JSON 拷贝过来,作为 Java API 的参数即可。
5. 文档操作
5.1 添加文档
先来看文档的添加操作。
如下表示我想给一个名为 books 的索引中添加一个 id 为 890 的书:
@Test
public void test07() throws IOException {
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
Book book = new Book();
book.setId(890);
book.setName("深入理解Java虚拟机");
book.setAuthor("xxx");//添加一个文档
//这是一个同步请求,请求会卡在这里
IndexResponse response = client.index(i -> i.index("books").document(book).id("890"));
System.out.println("response.result() = "+ response.result());
System.out.println("response.id() = "+ response.id());
System.out.println("response.seqNo() = "+ response.seqNo());
System.out.println("response.index() = "+ response.index());
System.out.println("response.shards() = "+ response.shards());}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
添加成功之后,返回的 IndexResponse 对象其实就是对下面这个 JSON 的封装:
现在我们只需要调用相应的方法,就可以获取到 JSON 相关的属性了。
5.2 删除文档
如下表示删除 books 索引中 id 为 891 的文档:
@Test
public void test09(){
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchAsyncClient client = new ElasticsearchAsyncClient(transport);
client.delete(d -> d.index("books").id("891")).whenComplete((resp, e) -> {
System.out.println("resp.result() = " + resp.result());
});
}