Elasticsearch Java API - 客户端连接

╰半橙微兮° 2023-08-17 15:31 180阅读 0赞
  1. package com.java1234;
  2. import com.google.gson.JsonObject;
  3. import org.elasticsearch.action.index.IndexResponse;
  4. import org.elasticsearch.client.transport.TransportClient;
  5. import org.elasticsearch.common.settings.Settings;
  6. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  7. import org.elasticsearch.common.xcontent.XContentType;
  8. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  9. import org.junit.After;
  10. import org.junit.Before;
  11. import org.junit.Test;
  12. import java.net.InetAddress;
  13. /**
  14. * @author XXL
  15. * @create 2019-08-04 13:05
  16. */
  17. public class ESConn {
  18. protected TransportClient client;
  19. @Before
  20. public void setUp() throws Exception {
  21. Settings esSettings = Settings.builder()
  22. .put("cluster.name", "my-application") //设置ES实例的名称
  23. // 这个不能乱加, 加了报错啊
  24. // .put("client.transport.sniff", true) //自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
  25. .build();
  26. /**
  27. * 这里的连接方式指的是没有安装x-pack插件,如果安装了x-pack则参考{@link ElasticsearchXPackClient}
  28. * 1. java客户端的方式是以tcp协议在9300端口上进行通信
  29. * 2. http客户端的方式是以http协议在9200端口上进行通信
  30. */
  31. client = new PreBuiltTransportClient(esSettings)
  32. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("公网ip"), 9300));
  33. System.out.println("ElasticsearchClient 连接成功");
  34. }
  35. @Test
  36. public void testClientConnection() throws Exception {
  37. System.out.println(client);
  38. JsonObject jsonObject=new JsonObject();
  39. jsonObject.addProperty("name", "java 编程思想");
  40. jsonObject.addProperty("publishDate", "2018-11-11");
  41. jsonObject.addProperty("price", 100);
  42. IndexResponse response=client.prepareIndex("book", "java", "1")
  43. .setSource(jsonObject.toString(), XContentType.JSON).get();
  44. System.out.println("索引名称:"+response.getIndex());
  45. System.out.println("类型:"+response.getType());
  46. System.out.println("文档ID:"+response.getId());
  47. System.out.println("当前实例状态:"+response.status());
  48. System.out.println("--------------------------");
  49. }
  50. @After
  51. public void tearDown() throws Exception {
  52. if (client != null) {
  53. client.close();
  54. }
  55. }
  56. }

  

运行结果:

708681-20190811000216047-1882017667.png

转载于:https://www.cnblogs.com/Uzai/p/11333592.html

发表评论

表情:
评论列表 (有 0 条评论,180人围观)

还没有评论,来说两句吧...

相关阅读