pox.xml文件添加以下内容

  1. <dependency>
  2. <groupId>org.elasticsearch.client</groupId>
  3. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  4. <version>6.3.2</version>
  5. </dependency>

新建ESHighLevelRestUtil.java

  1. package com;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.apache.http.HttpHost;
  5. import org.elasticsearch.ElasticsearchException;
  6. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
  7. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
  8. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  9. import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
  10. import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
  11. import org.elasticsearch.action.delete.DeleteRequest;
  12. import org.elasticsearch.action.delete.DeleteResponse;
  13. import org.elasticsearch.action.index.IndexRequest;
  14. import org.elasticsearch.action.index.IndexResponse;
  15. import org.elasticsearch.action.support.replication.ReplicationResponse;
  16. import org.elasticsearch.action.DocWriteResponse;
  17. import org.elasticsearch.client.RestClient;
  18. import org.elasticsearch.client.RestHighLevelClient;
  19. import org.elasticsearch.common.settings.Settings;
  20. import org.elasticsearch.common.xcontent.XContentType;
  21. import org.elasticsearch.rest.RestStatus;
  22. public class ESHighLevelRestUtil {
  23. static RestHighLevelClient client = new RestHighLevelClient(
  24. RestClient.builder(new HttpHost("172.19.12.249", 9200, "http")));
  25. /**
  26. * 验证索引是否存在
  27. *
  28. * @param index
  29. * 索引名称
  30. * @return
  31. * @throws Exception
  32. */
  33. public boolean indexExists(String index) throws Exception {
  34. GetIndexRequest request = new GetIndexRequest();
  35. request.indices(index);
  36. request.local(false);
  37. request.humanReadable(true);
  38. boolean exists = client.indices().exists(request);
  39. return exists;
  40. }
  41. /**
  42. *
  43. * @param index
  44. * @param indexType
  45. * @param properties
  46. * 结构: {name:{type:text}} {age:{type:integer}}
  47. * @return
  48. * @throws Exception
  49. */
  50. public boolean indexCreate(String index, String indexType,
  51. Map<String, Object> properties) throws Exception {
  52. if (indexExists(index)) {
  53. return true;
  54. }
  55. CreateIndexRequest request = new CreateIndexRequest(index);
  56. request.settings(Settings.builder().put("index.number_of_shards", 3)
  57. .put("index.number_of_replicas", 2));
  58. Map<String, Object> jsonMap = new HashMap<>();
  59. Map<String, Object> mapping = new HashMap<>();
  60. mapping.put("properties", properties);
  61. jsonMap.put(indexType, mapping);
  62. request.mapping(indexType, jsonMap);
  63. CreateIndexResponse createIndexResponse = client.indices().create(
  64. request);
  65. boolean acknowledged = createIndexResponse.isAcknowledged();
  66. return acknowledged;
  67. }
  68. /**
  69. * 删除索引
  70. *
  71. * @param index
  72. * @return
  73. * @throws Exception
  74. */
  75. public boolean indexDelete(String index) throws Exception {
  76. try {
  77. DeleteIndexRequest request = new DeleteIndexRequest(index);
  78. DeleteIndexResponse deleteIndexResponse = client.indices().delete(
  79. request);
  80. return deleteIndexResponse.isAcknowledged();
  81. } catch (ElasticsearchException exception) {
  82. if (exception.status() == RestStatus.NOT_FOUND) {
  83. return true;
  84. } else {
  85. return false;
  86. }
  87. }
  88. }
  89. /**
  90. * 创建更新文档
  91. *
  92. * @param index
  93. * @param indexType
  94. * @param documentId
  95. * @param josonStr
  96. * @return
  97. * @throws Exception
  98. */
  99. public boolean documentCreate(String index, String indexType,
  100. String documentId, String josonStr) throws Exception {
  101. IndexRequest request = new IndexRequest(index, indexType, documentId);
  102. request.source(josonStr, XContentType.JSON);
  103. IndexResponse indexResponse = client.index(request);
  104. if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
  105. || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  106. return true;
  107. }
  108. ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
  109. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  110. return true;
  111. }
  112. if (shardInfo.getFailed() > 0) {
  113. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
  114. .getFailures()) {
  115. throw new Exception(failure.reason());
  116. }
  117. }
  118. return false;
  119. }
  120. /**
  121. * 创建更新索引
  122. *
  123. * @param index
  124. * @param indexType
  125. * @param documentId
  126. * @param map
  127. * @return
  128. * @throws Exception
  129. */
  130. public boolean documentCreate(String index, String indexType,
  131. String documentId, Map<String, Object> map) throws Exception {
  132. IndexRequest request = new IndexRequest(index, indexType, documentId);
  133. request.source(map);
  134. IndexResponse indexResponse = client.index(request);
  135. if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
  136. || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  137. return true;
  138. }
  139. ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
  140. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  141. return true;
  142. }
  143. if (shardInfo.getFailed() > 0) {
  144. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
  145. .getFailures()) {
  146. throw new Exception(failure.reason());
  147. }
  148. }
  149. return false;
  150. }
  151. /**
  152. * 创建索引
  153. *
  154. * @param index
  155. * @param indexType
  156. * @param josonStr
  157. * @return
  158. * @throws Exception
  159. */
  160. public String documentCreate(String index, String indexType, String josonStr)
  161. throws Exception {
  162. IndexRequest request = new IndexRequest(index, indexType);
  163. request.source(josonStr, XContentType.JSON);
  164. IndexResponse indexResponse = client.index(request);
  165. String id = indexResponse.getId();
  166. if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
  167. || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  168. return id;
  169. }
  170. ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
  171. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  172. return id;
  173. }
  174. if (shardInfo.getFailed() > 0) {
  175. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
  176. .getFailures()) {
  177. throw new Exception(failure.reason());
  178. }
  179. }
  180. return null;
  181. }
  182. /**
  183. * 创建索引
  184. *
  185. * @param index
  186. * @param indexType
  187. * @param map
  188. * @return
  189. * @throws Exception
  190. */
  191. public String documentCreate(String index, String indexType,
  192. Map<String, Object> map) throws Exception {
  193. IndexRequest request = new IndexRequest(index, indexType);
  194. request.source(map);
  195. IndexResponse indexResponse = client.index(request);
  196. String id = indexResponse.getId();
  197. if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
  198. || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
  199. return id;
  200. }
  201. ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
  202. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  203. return id;
  204. }
  205. if (shardInfo.getFailed() > 0) {
  206. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
  207. .getFailures()) {
  208. throw new Exception(failure.reason());
  209. }
  210. }
  211. return null;
  212. }
  213. public boolean documentDelete(String index, String indexType,
  214. String documentId) throws Exception {
  215. DeleteRequest request = new DeleteRequest(index, indexType, documentId);
  216. DeleteResponse deleteResponse = client.delete(request);
  217. if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
  218. return true;
  219. }
  220. ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
  221. if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
  222. return true;
  223. }
  224. if (shardInfo.getFailed() > 0) {
  225. for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
  226. .getFailures()) {
  227. throw new Exception(failure.reason());
  228. }
  229. }
  230. return false;
  231. }
  232. }

新建ESHighLevelRestTest.java

  1. package com;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.apache.http.HttpHost;
  5. import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
  6. import org.elasticsearch.client.RestClient;
  7. import org.elasticsearch.client.RestHighLevelClient;
  8. public class ESHighLevelRestTest {
  9. public static void main(String[] args) throws Exception {
  10. // TODO Auto-generated method stub
  11. ESHighLevelRestUtil util = new ESHighLevelRestUtil();
  12. System.out.println(util.indexExists("indextest001"));
  13. Map<String, Object> map = new HashMap<String, Object>();
  14. map.put("name", new HashMap() {
  15. {
  16. put("type", "text");
  17. }
  18. });
  19. map.put("age", new HashMap() {
  20. {
  21. put("type", "double");
  22. }
  23. });
  24. map.put("sex", new HashMap() {
  25. {
  26. put("type", "double");
  27. }
  28. });
  29. map.put("address", new HashMap() {
  30. {
  31. put("type", "text");
  32. }
  33. });
  34. // 创建主题
  35. util.indexCreate("indextest005", "sx", map);
  36. //创建文档1
  37. System.out.println(util.documentCreate("indextest005", "sx",
  38. new HashMap<String,Object>() {
  39. {
  40. put("name", "名称1");
  41. put("age", 18);
  42. put("sex", 10);
  43. put("address", "地址1");
  44. }
  45. }));
  46. //创建更新文档2
  47. System.out.println(util.documentCreate("indextest005", "sx", "1",
  48. new HashMap<String,Object>() {
  49. {
  50. put("name", "名称2");
  51. put("age", 18);
  52. put("sex", 10);
  53. put("address", "地址2");
  54. }
  55. }));
  56. //删除文档
  57. System.out.println(util.documentDelete("indextest005", "sx", "1"));
  58. }
  59. }

参考:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-overview.html

相互学习,如有不正确的地方欢迎指正

elasticsearch Java High Level REST 相关操作封装的更多相关文章

  1. java 线程 原子类相关操作演示样例 thinking in java4 文件夹21.3.4

    java 线程  原子类相关操作演示样例 package org.rui.thread.volatiles; import java.util.Timer; import java.util.Time ...

  2. 使用Java High Level REST Client操作elasticsearch

    Java高级别REST客户端(The Java High Level REST Client)以后简称高级客户端,内部仍然是基于低级客户端.它提供了更多的API,接受请求对象作为参数并返回响应对象,由 ...

  3. 使用Java Low Level REST Client操作elasticsearch

    Java REST客户端有两种风格: Java低级别REST客户端(Java Low Level REST Client,以后都简称低级客户端算了,难得码字):Elasticsearch的官方low- ...

  4. 数据结构Java实现04---树及其相关操作

    首先什么是树结构? 树是一种描述非线性层次关系的数据结构,树是n个数据结点的集合,这些集结点包含一个根节点,根节点下有着互相不交叉的子集合,这些子集合便是根节点的子树. 树的特点 在一个树结构中,有且 ...

  5. java 的Date 日期相关操作

    String 与 Date互转(1)基于SimpleDateFormat实现: package com.bky.df; import java.text.ParseException; import ...

  6. java实现安全证书相关操作

    https://blog.csdn.net/zhushanzhi/article/details/77864516 版权声明:本文为博主原创文章,未经博主允许不得转载. package test; i ...

  7. java实现二叉树的相关操作

    import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ ...

  8. POI开发:Java中的Excel相关操作

    一.Apache POI 1.简介: Apache POI支持大多数中小规模的应用程序开发,提供API给Java程序对Microsoft Office格式档案读和写的功能,呈现和文本提取是它的主要特点 ...

  9. Elasticsearch Java Low Level REST Client(嗅探器)

    https://segmentfault.com/a/1190000016828977?utm_source=tag-newest#articleHeader0 嗅探器 允许从正在运行的Elastic ...

随机推荐

  1. MetaException(message:For direct MetaStore DB connections, we don't support retries at the client level.)

    在mysql中执行以下命令:  drop database hive;  create database hive;  alter database hive character set latin1 ...

  2. 百度MIP技术快速入门(上)

    前言 「本文假定读者已经有初级的前端开发知识,包括HTML.CSS.」 百度在一年前推出了称为 MIP(Mobile Instant Pages)的前端开发组件,主要目的是加速移动端网页的显示.MIP ...

  3. 转:C++ 11 Lambda表达式

    转:https://www.cnblogs.com/DswCnblog/p/5629165.html C++11的一大亮点就是引入了Lambda表达式.利用Lambda表达式,可以方便的定义和创建匿名 ...

  4. 处理警告:编码 GBK 的不可映射字符

    怎么处理警告:编码 GBK 的不可映射字符:javac -encoding UTF-8 XX.java使用-encoding参数指明编码方式: 或者 用记事本打开文件,然后另存为,选择ANSI编码,覆 ...

  5. Pasha and Tea

    Pasha and Tea time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  6. hashmap:cr:csdn

    HashMap相关问题 1.你用过HashMap吗?什么是HashMap?你为什么用到它? 用过,HashMap是基于哈希表的Map接口的非同步实现,它允许null键和null值,且HashMap依托 ...

  7. Original blog

    其实也没几篇... I am still too young. http://blog.csdn.net/greyqz 没什么东西,就别去翻了... 还是博客园好用,发博客不用审核,CSDN审核不好玩

  8. SelfCert wcf中 生成x5.09证书的工具

    http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programma ...

  9. 用 Flask 来写个轻博客 (30) — 使用 Flask-Admin 增强文章管理功能

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 实现文章管理功能 实现效果 前文列表 用 Flask 来写个 ...

  10. java构造器内部多态方法

    public class TestC { public static void main(String []args) { new Graph(5); }}class Grp{ void draw() ...