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

先说以前的创建方式:

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

  1. /**
  2. * 获取连接, 第一种方式
  3. * @throws Exception
  4. */
  5. // @Before
  6. public void before() throws Exception {
  7. Map<String, String> map = new HashMap<String, String>();
  8. map.put("cluster.name", "elasticsearch_wenbronk");
  9. Settings.Builder settings = Settings.builder().put(map);
  10. client = TransportClient.builder().settings(settings).build()
  11. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("www.wenbronk.com"), Integer.parseInt("")));
  12. }
  13.  
  14. /**
  15. * 获取连接, 第二种方式
  16. * @throws Exception
  17. */
  18. @Before
  19. public void before11() throws Exception {
  20. // 创建客户端, 使用的默认集群名, "elasticSearch"
  21. // client = TransportClient.builder().build()
  22. // .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("www.wenbronk.com"), 9300));
  23.  
  24. // 通过setting对象指定集群配置信息, 配置的集群名
  25. Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch_wenbronk") // 设置集群名
  26. // .put("client.transport.sniff", true) // 开启嗅探 , 开启后会一直连接不上, 原因未知
  27. // .put("network.host", "192.168.50.37")
  28. .put("client.transport.ignore_cluster_name", true) // 忽略集群名字验证, 打开后集群名字不对也能连接上
  29. // .put("client.transport.nodes_sampler_interval", 5) //报错,
  30. // .put("client.transport.ping_timeout", 5) // 报错, ping等待时间,
  31. .build();
  32. client = TransportClient.builder().settings(settings).build()
  33. .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("192.168.50.37", )));
  34. // 默认5s
  35. // 多久打开连接, 默认5s
  36. System.out.println("success connect");
  37. }

最新的创建方式:

  1. package com.wenbronk.elasticsearch.usage.highLevel;
  2.  
  3. import com.google.common.collect.Lists;
  4. import org.apache.http.HttpHost;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import org.junit.jupiter.api.AfterEach;
  8. import org.junit.jupiter.api.BeforeEach;
  9.  
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13.  
  14. public class RestHighLevelClientParent {
  15.  
  16. public static final String HOST = "10.124.147.22,10.124.147.23,10.124.147.32";
  17. public static final Integer PORT = ;
  18.  
  19. protected RestHighLevelClient client;
  20.  
  21. @BeforeEach
  22. public void testBefore() {
  23.  
  24. ArrayList<HttpHost> hosts = Lists.newArrayList();
  25.  
  26. Arrays.stream(HOST.split(",")).forEach(host -> {
  27. hosts.add(new HttpHost(host, PORT, "http"));
  28. });
  29.  
  30. client = new RestHighLevelClient(RestClient.builder(hosts.toArray(new HttpHost[])));
  31.  
  32. }
  33.  
  34. @AfterEach
  35. public void testAfter() throws IOException {
  36. client.close();
  37. }
  38.  
  39. }

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

1), index

  1. @Test
  2. public void testAsync() throws IOException, InterruptedException {
  3. CountDownLatch countDownLatch = new CountDownLatch();
  4. XContentBuilder object = XContentFactory.jsonBuilder()
  5. .startObject()
  6. .field("user", "wenbronk")
  7. .timeField("postData", new Date())
  8. .field("message", "message format from xcontent")
  9. .endObject();
  10. IndexRequest source = new IndexRequest("test", "doc", "").source(object);
  11. client.indexAsync(source, new ActionListener<IndexResponse>() {
  12. @Override
  13. public void onResponse(IndexResponse indexResponse) {
  14. String id = indexResponse.getId();
  15. String index = indexResponse.getIndex();
  16. String type = indexResponse.getType();
  17.  
  18. if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
  19.  
  20. }
  21. if (indexResponse.getResult() == DocWriteResponse.Result.DELETED) {
  22.  
  23. }
  24. if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  25.  
  26. }
  27.  
  28. ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
  29. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  30. // 有失败的
  31. }
  32. // 对失败的进行处理
  33. if (shardInfo.getFailed() != ) {
  34. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
  35. String reason = failure.reason();
  36. }
  37. }
  38. countDownLatch.countDown();
  39. }
  40.  
  41. @Override
  42. public void onFailure(Exception e) {
  43. if (e instanceof ElasticsearchException) {
  44. ElasticsearchException e1 = (ElasticsearchException) e;
  45. if (e1.status() == RestStatus.CONFLICT) {
  46. System.out.println("版本冲突 ");
  47. }
  48. }
  49. }
  50. });
  51. countDownLatch.await();
  52. }

2), get

  1. @Test
  2. public void testGet() throws InterruptedException {
  3. CountDownLatch countDownLatch = new CountDownLatch();
  4. // index, type, id
  5. GetRequest request = new GetRequest("test", "doc", "");
  6.  
  7. // 可选的添加参数
  8. // disabled _source retrieval
  9. // request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
  10.  
  11. // Configure source inclusion for specific fields
  12. // String[] includes = new String[]{"message", "*Data"};
  13. // String[] excludes = Strings.EMPTY_ARRAY;
  14. // FetchSourceContext fetchSourceContext =
  15. // new FetchSourceContext(true, includes, excludes);
  16. // request.fetchSourceContext(fetchSourceContext);
  17.  
  18. // Configure source exclusion for specific fields
  19. // request.storedFields("message");
  20.  
  21. request.routing("routing");
  22. request.parent("parent");
  23. request.preference("preference");
  24. request.realtime(false);
  25. request.refresh(true);
  26. request.version();
  27. request.versionType(VersionType.EXTERNAL);
  28.  
  29. // 对response处理
  30. client.getAsync(request, new ActionListener<GetResponse>() {
  31. @Override
  32. public void onResponse(GetResponse getResponse) {
  33. String type = getResponse.getType();
  34. String index = getResponse.getIndex();
  35. String id = getResponse.getId();
  36. Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
  37. sourceAsMap.entrySet().forEach(entry -> System.out.println(entry.getKey() + " : " + entry.getValue()));
  38.  
  39. countDownLatch.countDown();
  40. }
  41.  
  42. @Override
  43. public void onFailure(Exception e) {
  44. // 可能的异常, 1, 不存在, 2 conflict
  45. if (e instanceof ElasticsearchException) {
  46. if (((ElasticsearchException) e).status() == RestStatus.NOT_FOUND) {
  47. System.out.println("要找的id不存在");
  48. }
  49.  
  50. if (((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
  51. System.out.println("conflict ");
  52. }
  53. }
  54. countDownLatch.countDown();
  55. }
  56. });
  57. countDownLatch.await();
  58. }

3), update

  1. @Test
  2. public void testResponse() throws IOException {
  3. XContentBuilder builder = XContentFactory.jsonBuilder()
  4. .startObject()
  5. .timeField("updated", new Date())
  6. .field("reason", "daily update")
  7. .endObject();
  8. UpdateRequest request = new UpdateRequest("posts", "doc", "")
  9. .doc(builder);
  10.  
  11. client.updateAsync(request, new ActionListener<UpdateResponse>() {
  12. @Override
  13. public void onResponse(UpdateResponse updateResponse) {
  14. String index = updateResponse.getIndex();
  15. String type = updateResponse.getType();
  16. String id = updateResponse.getId();
  17. long version = updateResponse.getVersion();
  18. if (updateResponse.getResult() == DocWriteResponse.Result.CREATED) {
  19.  
  20. } else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  21.  
  22. } else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED) {
  23.  
  24. } else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP) {
  25.  
  26. }
  27.  
  28. GetResult result = updateResponse.getGetResult();
  29. if (result.isExists()) {
  30. String sourceAsString = result.sourceAsString();
  31. Map<String, Object> sourceAsMap = result.sourceAsMap();
  32. byte[] sourceAsBytes = result.source();
  33. } else {
  34.  
  35. }
  36.  
  37. ReplicationResponse.ShardInfo shardInfo = updateResponse.getShardInfo();
  38. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  39.  
  40. }
  41. if (shardInfo.getFailed() > ) {
  42. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
  43. String reason = failure.reason();
  44. }
  45. }
  46. }
  47.  
  48. @Override
  49. public void onFailure(Exception e) {
  50.  
  51. }
  52. });
  53. }

4), delete

  1. @Test
  2. public void testDelete() {
  3. DeleteRequest deleteRequest = new DeleteRequest("test", "doc", "");
  4.  
  5. client.deleteAsync(deleteRequest, new ActionListener<DeleteResponse>() {
  6. @Override
  7. public void onResponse(DeleteResponse deleteResponse) {
  8. String index = deleteResponse.getIndex();
  9. String type = deleteResponse.getType();
  10. String id = deleteResponse.getId();
  11. long version = deleteResponse.getVersion();
  12. ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
  13. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  14.  
  15. }
  16. if (shardInfo.getFailed() > ) {
  17. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
  18. String reason = failure.reason();
  19. }
  20. }
  21. }
  22.  
  23. @Override
  24. public void onFailure(Exception e) {
  25. // 可能的异常, 1, 不存在, 2 conflict
  26. if (e instanceof ElasticsearchException) {
  27. if (((ElasticsearchException) e).status() == RestStatus.NOT_FOUND) {
  28. System.out.println("id不存在");
  29. }
  30. if (((ElasticsearchException) e).status() == RestStatus.CONFLICT) {
  31. System.out.println("conflict ");
  32. }
  33. }
  34. }
  35. });
  36.  
  37. }

5), bulk

  1. @Test
  2. public void testBulk() {
  3. BulkRequest request = new BulkRequest();
  4. request.add(new DeleteRequest("posts", "doc", ""));
  5. request.add(new UpdateRequest("posts", "doc", "")
  6. .doc(XContentType.JSON,"other", "test"));
  7. request.add(new IndexRequest("posts", "doc", "")
  8. .source(XContentType.JSON,"field", "baz"));
  9.  
  10. // 可选的参数
  11. request.timeout(TimeValue.timeValueMinutes());
  12. request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
  13. request.waitForActiveShards();
  14.  
  15. // 异步处理
  16. client.bulkAsync(request, new ActionListener<BulkResponse>() {
  17. @Override
  18. public void onResponse(BulkResponse bulkItemResponses) {
  19. for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
  20. DocWriteResponse itemResponse = bulkItemResponse.getResponse();
  21.  
  22. if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX || bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) {
  23. IndexResponse indexResponse = (IndexResponse) itemResponse;
  24.  
  25. } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) {
  26. UpdateResponse updateResponse = (UpdateResponse) itemResponse;
  27.  
  28. } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) {
  29. DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
  30. }
  31. // 失败的返回
  32. if (bulkItemResponse.isFailed()) {
  33. BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
  34.  
  35. }
  36. }
  37. }
  38.  
  39. @Override
  40. public void onFailure(Exception e) {
  41.  
  42. }
  43. });
  44. }

6), bulkprocess

  1. @Test
  2. public void testBulkProcess() throws InterruptedException {
  3. // create bulkprocessor
  4. BulkProcessor.Builder builder = BulkProcessor.builder(client::bulkAsync, new BulkProcessor.Listener() {
  5. @Override
  6. public void beforeBulk(long executionId, BulkRequest request) {
  7. int numberOfActions = request.numberOfActions();
  8. logger.debug("Executing bulk [{}] with {} requests",
  9. executionId, numberOfActions);
  10. }
  11.  
  12. @Override
  13. public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
  14. if (response.hasFailures()) {
  15. logger.warn("Bulk [{}] executed with failures", executionId);
  16. } else {
  17. logger.debug("Bulk [{}] completed in {} milliseconds",
  18. executionId, response.getTook().getMillis());
  19. }
  20. }
  21.  
  22. // when failure, will be called
  23. @Override
  24. public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
  25. logger.error("Failed to execute bulk", failure);
  26. }
  27. });
  28.  
  29. // 添加参数
  30. builder.setBulkActions(); // 刷新时间
  31. builder.setBulkSize(new ByteSizeValue(1L, ByteSizeUnit.MB)); // 刷新长度
  32. builder.setConcurrentRequests(); // 并发度
  33. builder.setFlushInterval(TimeValue.timeValueSeconds(10L)); // 刷新周期
  34. builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), ));
  35.  
  36. BulkProcessor bulkProcessor = builder.build();
  37.  
  38. // 添加批量执行数据
  39. IndexRequest one = new IndexRequest("posts", "doc", "").
  40. source(XContentType.JSON, "title", "In which order are my Elasticsearch queries executed?");
  41. IndexRequest two = new IndexRequest("posts", "doc", "")
  42. .source(XContentType.JSON, "title", "Current status and upcoming changes in Elasticsearch");
  43. IndexRequest three = new IndexRequest("posts", "doc", "")
  44. .source(XContentType.JSON, "title", "The Future of Federated Search in Elasticsearch");
  45.  
  46. bulkProcessor.add(one);
  47. bulkProcessor.add(two);
  48. bulkProcessor.add(three);
  49.  
  50. boolean terminated = bulkProcessor.awaitClose(30L, TimeUnit.SECONDS);
  51. bulkProcessor.close();
  52. }

7), multiget

  1. @Test
  2. public void testMultiGet() {
  3. MultiGetRequest request = new MultiGetRequest();
  4. request.add(new MultiGetRequest.Item("index", "type", "example_id"));
  5. request.add(new MultiGetRequest.Item("index", "type", "another_id"));
  6.  
  7. client.multiGetAsync(request, new ActionListener<MultiGetResponse>() {
  8. @Override
  9. public void onResponse(MultiGetResponse multiGetItemResponses) {
  10. MultiGetItemResponse firstItem = multiGetItemResponses.getResponses()[];
  11. assertNull(firstItem.getFailure());
  12. GetResponse firstGet = firstItem.getResponse();
  13. String index = firstItem.getIndex();
  14. String type = firstItem.getType();
  15. String id = firstItem.getId();
  16. if (firstGet.isExists()) {
  17. long version = firstGet.getVersion();
  18. String sourceAsString = firstGet.getSourceAsString();
  19. Map<String, Object> sourceAsMap = firstGet.getSourceAsMap();
  20. byte[] sourceAsBytes = firstGet.getSourceAsBytes();
  21. } else {
  22.  
  23. }
  24. }
  25.  
  26. @Override
  27. public void onFailure(Exception e) {
  28.  
  29. }
  30. });
  31.  
  32. }

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. 关于Lambda

    1. 查询时,包含关联子对象.如: 数据库中包含表Father和Son,映射实体如下: public class Father { public string Name{get;set;} publi ...

  2. stm32常识

    cmsis全称Cortex Microcontroller Software Interface Standard,就是Cortex微处理器软件接口标准 stm32每组gpio有7组端口,分别是2个3 ...

  3. USTC《现代软件工程》春季学期——第一次个人作业:词频统计

    截止日期 2018年3月29日23:59 要求 1. 对源文件(*.txt,*.cpp,*.h,*.cs,*.html,*.js,*.java,*.py,*.php等,文件夹内的所有文件)统计字符数. ...

  4. poj 2192 Zipper

    题目 刚开始本来觉得可以用队列来写,但是 例如 ta te teta,ta的t先出队列那就不行了,所以还得用dp dp[i][j] 表示A前i个字符与B前j个字符是否能构成C前i+j个字符 要使 dp ...

  5. python模块补充

    一.模块补充 configparser 1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有的section,并以列表的形式返回 -opti ...

  6. zoj2607

    题意:如左图,给定A,B,C,D的面积分别为大于等于a,b,c,d,求最小的面积 思路:因为a,b肯定有一个是满的(不然还可压缩到更小),同理,ac,bd,cd都只有一个是满的,所以有可能是对角满的, ...

  7. day05_雷神_函数进阶

    #day05 1.迭代器 1.1可迭代对象 str,list,tuple,dict,set,range,文件句柄 等都是可迭代对象 第一种方法:在该对象中,含有__iter__方法的就是可迭代对象,遵 ...

  8. 安装Chrome浏览器

    Ubuntu 16.04下安装64位谷歌Chrome浏览器 在 Ubuntu 16.04 中,要想使用谷歌的 Chrome 浏览器,可以通过命令行的方式手动安装. 1.进入 Ubuntu 16.04 ...

  9. Android-Kotlin-when&类型推断

    Kotlin的when表达式 TextEngine 描述文字处理对象: package cn.kotlin.kotlin_base02 /** * 描述文字处理对象 * * val textConte ...

  10. mysql命令行客户端结果分页浏览

    转载请注明出处:http://xiezhenye.com/2008/06/mysql%e5%91%bd%e4%bb%a4%e8%a1%8c%e5%ae%a2%e6%88%b7%e7%ab%af%e7% ...