在6.x以前, 使用最多的是transportclient, 但在7.x会被废弃,

先说以前的创建方式:

具体可见:https://www.cnblogs.com/wenbronk/p/6383194.html

    /**
* 获取连接, 第一种方式
* @throws Exception
*/
// @Before
public void before() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("cluster.name", "elasticsearch_wenbronk");
Settings.Builder settings = Settings.builder().put(map);
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("www.wenbronk.com"), Integer.parseInt("")));
} /**
* 获取连接, 第二种方式
* @throws Exception
*/
@Before
public void before11() throws Exception {
// 创建客户端, 使用的默认集群名, "elasticSearch"
// client = TransportClient.builder().build()
// .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("www.wenbronk.com"), 9300)); // 通过setting对象指定集群配置信息, 配置的集群名
Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch_wenbronk") // 设置集群名
// .put("client.transport.sniff", true) // 开启嗅探 , 开启后会一直连接不上, 原因未知
// .put("network.host", "192.168.50.37")
.put("client.transport.ignore_cluster_name", true) // 忽略集群名字验证, 打开后集群名字不对也能连接上
// .put("client.transport.nodes_sampler_interval", 5) //报错,
// .put("client.transport.ping_timeout", 5) // 报错, ping等待时间,
.build();
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("192.168.50.37", )));
// 默认5s
// 多久打开连接, 默认5s
System.out.println("success connect");
}

最新的创建方式:

package com.wenbronk.elasticsearch.usage.highLevel;

import com.google.common.collect.Lists;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays; public class RestHighLevelClientParent { public static final String HOST = "10.124.147.22,10.124.147.23,10.124.147.32";
public static final Integer PORT = ; protected RestHighLevelClient client; @BeforeEach
public void testBefore() { ArrayList<HttpHost> hosts = Lists.newArrayList(); Arrays.stream(HOST.split(",")).forEach(host -> {
hosts.add(new HttpHost(host, PORT, "http"));
}); client = new RestHighLevelClient(RestClient.builder(hosts.toArray(new HttpHost[]))); } @AfterEach
public void testAfter() throws IOException {
client.close();
} }

新的客户端, 对异步的处理方式和以前基本相同

1), index

@Test
public void testAsync() throws IOException, InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch();
XContentBuilder object = XContentFactory.jsonBuilder()
.startObject()
.field("user", "wenbronk")
.timeField("postData", new Date())
.field("message", "message format from xcontent")
.endObject();
IndexRequest source = new IndexRequest("test", "doc", "").source(object);
client.indexAsync(source, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
String id = indexResponse.getId();
String index = indexResponse.getIndex();
String type = indexResponse.getType(); if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) { }
if (indexResponse.getResult() == DocWriteResponse.Result.DELETED) { }
if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) { } ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
// 有失败的
}
// 对失败的进行处理
if (shardInfo.getFailed() != ) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
}
}
countDownLatch.countDown();
} @Override
public void onFailure(Exception e) {
if (e instanceof ElasticsearchException) {
ElasticsearchException e1 = (ElasticsearchException) e;
if (e1.status() == RestStatus.CONFLICT) {
System.out.println("版本冲突 ");
}
}
}
});
countDownLatch.await();
}

2), get

@Test
public void testGet() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch();
// index, type, id
GetRequest request = new GetRequest("test", "doc", ""); // 可选的添加参数
// disabled _source retrieval
// request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE); // Configure source inclusion for specific fields
// String[] includes = new String[]{"message", "*Data"};
// String[] excludes = Strings.EMPTY_ARRAY;
// FetchSourceContext fetchSourceContext =
// new FetchSourceContext(true, includes, excludes);
// request.fetchSourceContext(fetchSourceContext); // Configure source exclusion for specific fields
// request.storedFields("message"); request.routing("routing");
request.parent("parent");
request.preference("preference");
request.realtime(false);
request.refresh(true);
request.version();
request.versionType(VersionType.EXTERNAL); // 对response处理
client.getAsync(request, new ActionListener<GetResponse>() {
@Override
public void onResponse(GetResponse getResponse) {
String type = getResponse.getType();
String index = getResponse.getIndex();
String id = getResponse.getId();
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
sourceAsMap.entrySet().forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue())); countDownLatch.countDown();
} @Override
public void onFailure(Exception e) {
// 可能的异常, 1, 不存在, 2 conflict
if (e instanceof ElasticsearchException) {
if (((ElasticsearchException) e).status() == RestStatus.NOT_FOUND) {
System.out.println("要找的id不存在");
} if (((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
System.out.println("conflict ");
}
}
countDownLatch.countDown();
}
});
countDownLatch.await();
}

3), update

@Test
public void testResponse() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.timeField("updated", new Date())
.field("reason", "daily update")
.endObject();
UpdateRequest request = new UpdateRequest("posts", "doc", "")
.doc(builder); client.updateAsync(request, new ActionListener<UpdateResponse>() {
@Override
public void onResponse(UpdateResponse updateResponse) {
String index = updateResponse.getIndex();
String type = updateResponse.getType();
String id = updateResponse.getId();
long version = updateResponse.getVersion();
if (updateResponse.getResult() == DocWriteResponse.Result.CREATED) { } else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED) { } else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED) { } else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP) { } GetResult result = updateResponse.getGetResult();
if (result.isExists()) {
String sourceAsString = result.sourceAsString();
Map<String, Object> sourceAsMap = result.sourceAsMap();
byte[] sourceAsBytes = result.source();
} else { } ReplicationResponse.ShardInfo shardInfo = updateResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) { }
if (shardInfo.getFailed() > ) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
}
}
} @Override
public void onFailure(Exception e) { }
});
}

4), delete

@Test
public void testDelete() {
DeleteRequest deleteRequest = new DeleteRequest("test", "doc", ""); client.deleteAsync(deleteRequest, new ActionListener<DeleteResponse>() {
@Override
public void onResponse(DeleteResponse deleteResponse) {
String index = deleteResponse.getIndex();
String type = deleteResponse.getType();
String id = deleteResponse.getId();
long version = deleteResponse.getVersion();
ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) { }
if (shardInfo.getFailed() > ) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason = failure.reason();
}
}
} @Override
public void onFailure(Exception e) {
// 可能的异常, 1, 不存在, 2 conflict
if (e instanceof ElasticsearchException) {
if (((ElasticsearchException) e).status() == RestStatus.NOT_FOUND) {
System.out.println("id不存在");
}
if (((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
System.out.println("conflict ");
}
}
}
}); }

5), bulk

 @Test
public void testBulk() {
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest("posts", "doc", ""));
request.add(new UpdateRequest("posts", "doc", "")
.doc(XContentType.JSON,"other", "test"));
request.add(new IndexRequest("posts", "doc", "")
.source(XContentType.JSON,"field", "baz")); // 可选的参数
request.timeout(TimeValue.timeValueMinutes());
request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
request.waitForActiveShards(); // 异步处理
client.bulkAsync(request, new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkItemResponses) {
for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
DocWriteResponse itemResponse = bulkItemResponse.getResponse(); if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX || bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) {
IndexResponse indexResponse = (IndexResponse) itemResponse; } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) {
UpdateResponse updateResponse = (UpdateResponse) itemResponse; } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) {
DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
}
// 失败的返回
if (bulkItemResponse.isFailed()) {
BulkItemResponse.Failure failure = bulkItemResponse.getFailure(); }
}
} @Override
public void onFailure(Exception e) { }
});
}

6), bulkprocess

@Test
public void testBulkProcess() throws InterruptedException {
// create bulkprocessor
BulkProcessor.Builder builder = BulkProcessor.builder(client::bulkAsync, new BulkProcessor.Listener() {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
int numberOfActions = request.numberOfActions();
logger.debug("Executing bulk [{}] with {} requests",
executionId, numberOfActions);
} @Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
if (response.hasFailures()) {
logger.warn("Bulk [{}] executed with failures", executionId);
} else {
logger.debug("Bulk [{}] completed in {} milliseconds",
executionId, response.getTook().getMillis());
}
} // when failure, will be called
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
logger.error("Failed to execute bulk", failure);
}
}); // 添加参数
builder.setBulkActions(); // 刷新时间
builder.setBulkSize(new ByteSizeValue(1L, ByteSizeUnit.MB)); // 刷新长度
builder.setConcurrentRequests(); // 并发度
builder.setFlushInterval(TimeValue.timeValueSeconds(10L)); // 刷新周期
builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), )); BulkProcessor bulkProcessor = builder.build(); // 添加批量执行数据
IndexRequest one = new IndexRequest("posts", "doc", "").
source(XContentType.JSON, "title", "In which order are my Elasticsearch queries executed?");
IndexRequest two = new IndexRequest("posts", "doc", "")
.source(XContentType.JSON, "title", "Current status and upcoming changes in Elasticsearch");
IndexRequest three = new IndexRequest("posts", "doc", "")
.source(XContentType.JSON, "title", "The Future of Federated Search in Elasticsearch"); bulkProcessor.add(one);
bulkProcessor.add(two);
bulkProcessor.add(three); boolean terminated = bulkProcessor.awaitClose(30L, TimeUnit.SECONDS);
bulkProcessor.close();
}

7), multiget

@Test
public void testMultiGet() {
MultiGetRequest request = new MultiGetRequest();
request.add(new MultiGetRequest.Item("index", "type", "example_id"));
request.add(new MultiGetRequest.Item("index", "type", "another_id")); client.multiGetAsync(request, new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse multiGetItemResponses) {
MultiGetItemResponse firstItem = multiGetItemResponses.getResponses()[];
assertNull(firstItem.getFailure());
GetResponse firstGet = firstItem.getResponse();
String index = firstItem.getIndex();
String type = firstItem.getType();
String id = firstItem.getId();
if (firstGet.isExists()) {
long version = firstGet.getVersion();
String sourceAsString = firstGet.getSourceAsString();
Map<String, Object> sourceAsMap = firstGet.getSourceAsMap();
byte[] sourceAsBytes = firstGet.getSourceAsBytes();
} else { }
} @Override
public void onFailure(Exception e) { }
}); }

es-05-获取 resthighlevelclient及api的更多相关文章

  1. html5获取地理位置信息API

    html5获取地理位置信息API 在HTML5中,可以看下如何使用Geolocation API来获得用户的地理位置信息,如果该浏览器支持的话,且设备具有定位功能,就能够直接使用这组API来获取当前位 ...

  2. Struts2获取Servlet的api的两种方式,解决ParameterAware过时的问题

    servlet API通过ActionContext进行获取 Struts2对HttpServletRequest,HttpSession和ServletContext进行了封装,构造了3个Map对象 ...

  3. 微信小程序把玩(三十八)获取设备信息 API

    原文:微信小程序把玩(三十八)获取设备信息 API 获取设备信息这里分为四种, 主要属性: 网络信息wx.getNetWorkType, 系统信息wx.getSystemInfo, 重力感应数据wx. ...

  4. WIN10以后如果Manifest中不写支持WIN10的话,获取版本号的API获取的是6

    if TOSVersion.Major = 10 then  // 高版本的Delphi(比如Berlin)可以这样写 ShowMessage('Windows 10'); 或者: if Win32M ...

  5. 自动获取淘宝API数据访问的SessionKey

    最近在忙与淘宝做对接的工作,总体感觉淘宝的api文档做的还不错,不仅有沙箱测试环境,而且对于每一个api都可以通过api测试工具生成想要的代码,你完全可以先在测试工具中测试之后再进行代码的编写,这样就 ...

  6. 如何获取豆瓣电影 API Key

    如何获取豆瓣电影 API Key 豆瓣 API Key 不能使用了 ! solutions & !== ? https://frodo.douban.com/api/v2/subject_co ...

  7. Android 神兵利器之通过解析网页获取到的API数据合集,可拿来就用

    AppApis 前段时间,写了个做app的实战系列教程,其中一篇章提到了解析网页中的数据为己所用,看到大家的响应还不错,于是把自己以前解析过的网页数据都整理了下,开放出来,给更多的人使用,希望可以帮助 ...

  8. es的rest风格的api文档

    rest风格的api put http://127.0.0.1:9200/索引名称/类型名称/文档id (创建文档,指定文档id) post http://127.0.0.1:9200/索引名称/类型 ...

  9. OpenGL ES无法获取贴图数据原因

    最近在做一个项目,要从贴图中获取图像数据,查了很多资料,也琢磨很久,获取到的数据都是0.终于在一次偶然的机会,发现了端倪,成功了. 不得不说这"一分灵感"真的很重要 以下是在获取贴 ...

随机推荐

  1. Python 错误和异常小结[转]

    原文链接    http://blog.csdn.net/sinchb/article/details/8392827 事先说明哦,这不是一篇关于Python异常的全面介绍的文章,这只是在学习Pyth ...

  2. Android: Custom View和include标签的区别

    Custom View, 使用的时候是这样的: <com.example.home.alltest.view.MyCustomView android:id="@+id/customV ...

  3. 学习c++需要知道

    1.c++投入和经济产出比目前较低,c++很复杂,学习难度高.周期长.而且开发效率低. 2.但是c++趋紧于完美语言,它囊括了多种编程范型.它运行效率高,对计算机有着极致的控制能力.适用于低层. 3. ...

  4. Beta阶段第六篇Scrum冲刺博客-Day5

    1.站立式会议 提供当天站立式会议照片一张 2.每个人的工作 (有work item 的ID),并将其记录在码云项目管理中: 昨天已完成的工作. 张晨晨:完善收藏功能 郭琪容:收藏功能的实现 吴玲:完 ...

  5. ZUFE2480: 神奇的序列 2017-05-12 16:45 39人阅读 评论(0) 收藏

    2480: 神奇的序列 时间限制: 4 Sec  内存限制: 256 MB 提交: 31  解决: 15 [提交][状态][讨论版] 题目描述 序列a如下: a[0] = A; a[1] = B; a ...

  6. Hadoop/Spark相关面试问题总结

    面试回来之后把其中比较重要的问题记了下来写了个总结: (答案在后面) 1.简答说一下hadoop的map-reduce编程模型 2.hadoop的TextInputFormat作用是什么,如何自定义实 ...

  7. html5 datalist

    教程:http://www.w3school.com.cn/html5/html5_datalist.asp 提供自动完成的文本框

  8. ASP.NET MVC Owin 基本理解

    一.OWIN OWIN(Open Web Interface for .Net),定义了一个服务器(IIS)和Web应用程序(MVC,Webform)通信的标准接口,并且通过抽象层使得这两个在微软平台 ...

  9. UvaOJ 10167

    暴力搜索 #include<cstdio> struct node { int x; int y; }s[]; int main() { //freopen("input.txt ...

  10. 存储过程 Mvc 的调用

    /// <summary>        /// 根据条件,使用存储过程分页查询电影        /// </summary>        /// <param na ...