

Java 操作 ElasticSearch,so easy!
source link: https://mp.weixin.qq.com/s?__biz=MzI1NDY0MTkzNQ%3D%3D&%3Bmid=2247491909&%3Bidx=1&%3Bsn=10b941e22fd8f2a3c491b3894fb080ff
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

松哥原创的 Spring Boot 视频教程已经杀青,感兴趣的小伙伴戳这里--> Spring Boot+Vue+微人事视频教程
今天终于可以和小伙伴们分享通过 Java 来操作 ElasticSearch 的相关 API 啦~今天先来看一个简单的~
Java API 概览
手动发送 HTTP 请求
低级客户端
以下是视频笔记:
注意,笔记只是视频内容的一个简要记录,因此笔记内容比较简单,完整的内容可以查看视频。
25.ElasticSearch Java API 概览
Java 操作 Es 的方案:
-
直接使用 HTTP 请求
直接使用 HTTP 请求,去操作 Es。HTTP 请求工具,可以使用 Java 自带的 HttpUrlConnection,也可以使用一些 HTTP 请求库,例如 HttpClient、OKHttp、Spring 中的 RestTemplate 都可以。
这种方式有一个弊端,就是要自己组装请求参数,自己去解析响应的 JSON。
-
Low Level REST Client
用于 Es 的官方的低级客户端。这种方式允许通过 HTTP 与 Es 集群进行通信,但是请求时候的 JSON 参数和响应的 JSON 参数交给用户去处理。这种方式好处就是兼容所有的 Es 版本。但是就是数据处理比较麻烦。
-
High Level REST Client
用户 Es 的官方的高级客户端。这种方式允许通过 HTTP 与 Es 集群进行通信,它是基于 Low Level REST Client,但是提供了很多 API,开发者不需要自己去组装参数,也不需要自己去解析响应 JSON 。这种方式使用起来更加直接。但是需要注意,这种方式,所使用的依赖库的版本要和 Es 对应。
-
TransportClient
TransportClient 在 Es7 中已经被弃用,在 Es8 中将被完全删除。
26.ElasticSearch 普通 HTTP 请求
新建一个普通的 JavaSE 工程,添加如下代码:
public class HttpRequestTest {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:9200/books/_search?pretty=true");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
}
}
这里使用到的请求工具是 HttpURLConnection,开发者也可以使用 HttpClient、OkHttp、或者 Spring 中的 RestTemplate。
27.ElasticSearch Java Low Level REST Client
首先创建一个普通的 Maven 工程,添加如下依赖:
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.10.0</version>
</dependency>
</dependencies>
然后添加如下代码,发起一个简单的查询请求:
public class LowLevelTest {
public static void main(String[] args) throws IOException {
//1.构建一个 RestClient 对象
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http"),
new HttpHost("localhost", 9202, "http")
);
//2.如果需要在请求头中设置认证信息等,可以通过 builder 来设置
// builder.setDefaultHeaders(new Header[]{new BasicHeader("key","value")});
RestClient restClient = builder.build();
//3.构建请求
Request request = new Request("GET", "/books/_search");
//添加请求参数
request.addParameter("pretty","true");
//4.发起请求,发起请求有两种方式,可以同步,可以异步
//这种请求发起方式,会阻塞后面的代码
Response response = restClient.performRequest(request);
//5.解析 response,获取响应结果
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
//最后记得关闭 RestClient
restClient.close();
}
}
这个查询请求,是一个同步请求,在请求的过程中,后面的代码会被阻塞,如果不希望后面的代码被阻塞,可以使用异步请求。
public class LowLevelTest2 {
public static void main(String[] args) throws IOException {
//1.构建一个 RestClient 对象
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http"),
new HttpHost("localhost", 9202, "http")
);
//2.如果需要在请求头中设置认证信息等,可以通过 builder 来设置
// builder.setDefaultHeaders(new Header[]{new BasicHeader("key","value")});
RestClient restClient = builder.build();
//3.构建请求
Request request = new Request("GET", "/books/_search");
//添加请求参数
request.addParameter("pretty","true");
//4.发起请求,发起请求有两种方式,可以同步,可以异步
//异步请求
restClient.performRequestAsync(request, new ResponseListener() {
//请求成功的回调
@Override
public void onSuccess(Response response) {
//5.解析 response,获取响应结果
try {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
//最后记得关闭 RestClient
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//请求失败的回调
@Override
public void onFailure(Exception e) {
}
});
}
}
开发者在请求时,也可以携带 JSON 参数。
public class LowLevelTest3 {
public static void main(String[] args) throws IOException {
//1.构建一个 RestClient 对象
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http"),
new HttpHost("localhost", 9202, "http")
);
//2.如果需要在请求头中设置认证信息等,可以通过 builder 来设置
// builder.setDefaultHeaders(new Header[]{new BasicHeader("key","value")});
RestClient restClient = builder.build();
//3.构建请求
Request request = new Request("GET", "/books/_search");
//添加请求参数
request.addParameter("pretty","true");
//添加请求体
request.setEntity(new NStringEntity("{\"query\": {\"term\": {\"name\": {\"value\": \"java\"}}}}", ContentType.APPLICATION_JSON));
//4.发起请求,发起请求有两种方式,可以同步,可以异步
//异步请求
restClient.performRequestAsync(request, new ResponseListener() {
//请求成功的回调
@Override
public void onSuccess(Response response) {
//5.解析 response,获取响应结果
try {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
//最后记得关闭 RestClient
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//请求失败的回调
@Override
public void onFailure(Exception e) {
}
});
}
}
ElasticSearch 基础知识:
Recommend
-
63
环境Centos7.4Python2.7Pip2.7MySQL-python1.2.5Elasticsearc6.3.1Elasitcsearch6.3.2知识点调用PythonElasticsearhAPIPythonMysqldb使用DSL查询与聚合Pyehon列表操作代码#!/usr/bin/envpython#-*-coding:utf-8-*-#minyt2018.9.1#获取24小时内
-
26
本文来自51CTO博客, 原 文地址 https://blog.51cto.com/13981400/2402526...
-
33
1、前提 1.1 docker 安装elasticsearch 查询elasticsearch 版本 docker search elasticsearch 将对应的版本拉到本地 docker.elastic.co/elasticsearch/elasticsea...
-
14
松哥原创的 Spring Boot 视频教程已经杀青,感兴趣的小伙伴戳这里-->
-
2
go操作elasticsearch示例这里我使用elasticsearch官方给的go语言包(
-
5
ElasticSearch之映射常用操作 Posted on...
-
8
elasticsearch简单的CRUD操作 祈雨的博客 2018-09-09 create
-
7
公号:码农充电站pro 主页:https://codeshellme.github.io 本节介绍 ES 文档,索引及其基本操作。 1,ES 中的文档
-
6
常用Py3操作Elasticsearch方法 原创 以下内容是通过Python来操作Es的代码操作示例...
-
6
Elasticsearch学习系列二(基础操作) 本文将分为3块讲...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK