使用JestClient操作ElasticSearch

可参考: 
https://www.blog-china.cn/template/documentHtml/1484101683485.html

https://github.com/searchbox-io/Jest/blob/master/jest/src/test/java/io/searchbox/core/SearchScrollIntegrationTest.java

使用JestClient操作ElasticSearch,具体代码如下:

InitElasticSearchConfig.java

 
  1. package com.mdl.monitor.init;

  2.  
  3. import com.google.gson.GsonBuilder;

  4.  
  5. import io.searchbox.client.JestClient;

  6. import io.searchbox.client.JestClientFactory;

  7. import io.searchbox.client.config.HttpClientConfig;

  8.  
  9.  
  10. /**

  11. * 初始化es

  12. */

  13. public class InitElasticSearchConfig {

  14.  
  15. private JestClient client ;

  16.  
  17. public JestClient getClient() {

  18. return client;

  19. }

  20.  
  21. public InitElasticSearchConfig(String esUrl){

  22. client = getClientConfig(esUrl) ;

  23. }

  24.  
  25. public JestClient getClientConfig(String esUrl){

  26. JestClientFactory factory = new JestClientFactory();

  27. factory.setHttpClientConfig(new HttpClientConfig

  28. .Builder(esUrl)

  29. .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create())

  30. .multiThreaded(true)

  31. .readTimeout(10000)

  32. .build());

  33. JestClient client = factory.getObject();

  34. return client ;

  35. }

  36.  
  37. }

ElasticSearchDao.java

 
  1. package com.mdl.monitor.repositorys.elasticsearch;

  2.  
  3. import java.util.List;

  4.  
  5. import com.google.gson.JsonObject;

  6.  
  7. import io.searchbox.client.JestResult;

  8. import io.searchbox.core.SearchResult.Hit;

  9. import io.searchbox.core.SuggestResult;

  10.  
  11. /**

  12. * ES操作 抽象方法 基本包含所有基本操作

  13. */

  14. public interface ElasticSearchDao {

  15.  
  16. /**

  17. * 删除索引

  18. * @param type :当前删除document名称

  19. * @return

  20. */

  21. public JestResult deleteIndex(String type) ;

  22.  
  23. //清除缓存

  24. public JestResult clearCache() ;

  25.  
  26. /**

  27. * 关闭索引

  28. * @param type :文档表示的对象类别

  29. * @return

  30. */

  31. public JestResult closeIndex(String type) ;

  32.  
  33. //优化索引

  34. public JestResult optimizeIndex() ;

  35.  
  36. //刷新索引

  37. public JestResult flushIndex();

  38.  
  39. //判断索引是否存在

  40. public JestResult indicesExists();

  41.  
  42. //查看节点信息

  43. public JestResult nodesInfo();

  44.  
  45. //查看集群健康信息

  46. public JestResult health();

  47.  
  48. //节点状态

  49. public JestResult nodesStats();

  50.  
  51. /**

  52. * 更新Document

  53. * @param index :文档在哪存放

  54. * @param type : 文档表示的对象类别

  55. * @param id :文档唯一标识

  56. */

  57. public JestResult updateDocument(String script , String index,String type,String id);

  58.  
  59. /**

  60. * 删除Document

  61. * @param index :文档在哪存放

  62. * @param type : 文档表示的对象类别

  63. * @param id :文档唯一标识

  64. * @return

  65. */

  66. public JestResult deleteDocument(String index,String type,String id) ;

  67.  
  68. /**

  69. * 根据条件删除

  70. * @param index

  71. * @param type

  72. * @param params

  73. */

  74. public JestResult deleteDocumentByQuery(String index, String type, String params);

  75.  
  76.  
  77. /**

  78. * 获取Document

  79. * @param o :返回对象

  80. * @param index :文档在哪存放

  81. * @param type : 文档表示的对象类别

  82. * @param id :文档唯一标识

  83. * @return

  84. */

  85. public <T> JestResult getDocument(T o , String index , String type , String id) ;

  86.  
  87. //Suggestion

  88. public List<SuggestResult.Suggestion> suggest() ;

  89.  
  90. /**

  91. * 查询全部

  92. * @param index :文档在哪存放

  93. * @return

  94. */

  95. public <T> List<Hit<T,Void>> searchAll(String index , T o);

  96.  
  97. /**

  98. * 搜索

  99. * @param keyWord :搜索关键字

  100. * @return

  101. */

  102. public <T> List<Hit<T,Void>> createSearch(String keyWord , String type , T o , String... fields) ;

  103.  
  104. //bulkIndex操作

  105. public <T> void bulkIndex(String index , String type , T o) ;

  106.  
  107. /**

  108. * 创建索引

  109. * @param o :返回对象

  110. * @param index :文档在哪存放

  111. * @param type : 文档表示的对象类别

  112. * @return

  113. */

  114. public <T> JestResult createIndex(T o , String index , String type);

  115.  
  116. /**

  117. * 搜索事件流图表数据

  118. * @param param

  119. * @return

  120. */

  121. public JsonObject searchEvent(String param);

  122.  
  123. }

ElasticSearchDaoImpl.java

 
  1. package com.mdl.monitor.repositorys.elasticsearch.impl;

  2.  
  3. import java.io.IOException;

  4. import java.lang.reflect.Method;

  5. import java.util.Arrays;

  6. import java.util.List;

  7.  
  8. import org.apache.commons.logging.Log;

  9. import org.apache.commons.logging.LogFactory;

  10. import org.elasticsearch.index.query.QueryBuilders;

  11. import org.elasticsearch.search.builder.SearchSourceBuilder;

  12. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

  13. import org.springframework.beans.factory.annotation.Autowired;

  14. import org.springframework.stereotype.Service;

  15.  
  16. import com.mdl.monitor.init.InitElasticSearchConfig;

  17. import com.mdl.monitor.repositorys.elasticsearch.ElasticSearchDao;

  18. import com.google.gson.JsonObject;

  19. import com.google.gson.JsonParser;

  20.  
  21. import io.searchbox.client.JestResult;

  22. import io.searchbox.cluster.Health;

  23. import io.searchbox.cluster.NodesInfo;

  24. import io.searchbox.cluster.NodesStats;

  25. import io.searchbox.core.Bulk;

  26. import io.searchbox.core.Delete;

  27. import io.searchbox.core.Get;

  28. import io.searchbox.core.Index;

  29. import io.searchbox.core.Search;

  30. import io.searchbox.core.SearchResult;

  31. import io.searchbox.core.SearchResult.Hit;

  32. import io.searchbox.core.Suggest;

  33. import io.searchbox.core.SuggestResult;

  34. import io.searchbox.core.SuggestResult.Suggestion;

  35. import io.searchbox.core.Update;

  36. import io.searchbox.indices.ClearCache;

  37. import io.searchbox.indices.CloseIndex;

  38. import io.searchbox.indices.DeleteIndex;

  39. import io.searchbox.indices.Flush;

  40. import io.searchbox.indices.IndicesExists;

  41. import io.searchbox.indices.Optimize;

  42.  
  43. /**

  44. * es操作实现类

  45. */

  46.  
  47. @Service

  48. public class ElasticSearchDaoImpl implements ElasticSearchDao{

  49.  
  50. static protected final Log log = LogFactory.getLog(ElasticSearchDaoImpl.class.getName());

  51.  
  52. @Autowired

  53. private InitElasticSearchConfig esConfig ;

  54.  
  55. @Override

  56. public JestResult deleteIndex(String type) {

  57. DeleteIndex deleteIndex = new DeleteIndex.Builder(type).build();

  58. JestResult result = null ;

  59. try {

  60. result = esConfig.getClient().execute(deleteIndex);

  61. log.info("deleteIndex == " + result.getJsonString());

  62. } catch (IOException e) {

  63. e.printStackTrace();

  64. }

  65. return result ;

  66. }

  67.  
  68. @Override

  69. public JestResult clearCache() {

  70. ClearCache closeIndex = new ClearCache.Builder().build();

  71. JestResult result = null ;

  72. try {

  73. result = esConfig.getClient().execute(closeIndex);

  74. log.info("clearCache == " + result.getJsonString());

  75. } catch (IOException e) {

  76. e.printStackTrace();

  77. }

  78. return result ;

  79. }

  80.  
  81. @Override

  82. public JestResult closeIndex(String type) {

  83. CloseIndex closeIndex = new CloseIndex.Builder(type).build();

  84. JestResult result = null ;

  85. try {

  86. result = esConfig.getClient().execute(closeIndex);

  87. log.info("closeIndex == " + result.getJsonString());

  88. } catch (IOException e) {

  89. e.printStackTrace();

  90. }

  91. return result ;

  92. }

  93.  
  94. @Override

  95. public JestResult optimizeIndex() {

  96. Optimize optimize = new Optimize.Builder().build();

  97. JestResult result = null ;

  98. try {

  99. result = esConfig.getClient().execute(optimize);

  100. log.info("optimizeIndex == " + result.getJsonString());

  101. } catch (IOException e) {

  102. e.printStackTrace();

  103. }

  104. return result ;

  105. }

  106.  
  107. @Override

  108. public JestResult flushIndex() {

  109. Flush flush = new Flush.Builder().build();

  110. JestResult result = null ;

  111. try {

  112. result = esConfig.getClient().execute(flush);

  113. log.info("flushIndex == " + result.getJsonString());

  114. } catch (IOException e) {

  115. e.printStackTrace();

  116. }

  117. return result ;

  118. }

  119.  
  120. @Override

  121. public JestResult indicesExists() {

  122. IndicesExists indicesExists = new IndicesExists.Builder("article").build();

  123. JestResult result = null ;

  124. try {

  125. result = esConfig.getClient().execute(indicesExists);

  126. log.info("indicesExists == " + result.getJsonString());

  127. } catch (IOException e) {

  128. e.printStackTrace();

  129. }

  130. return result ;

  131. }

  132.  
  133. @Override

  134. public JestResult nodesInfo() {

  135. NodesInfo nodesInfo = new NodesInfo.Builder().build();

  136. JestResult result = null ;

  137. try {

  138. result = esConfig.getClient().execute(nodesInfo);

  139. log.info("nodesInfo == " + result.getJsonString());

  140. } catch (IOException e) {

  141. e.printStackTrace();

  142. }

  143. return result ;

  144. }

  145.  
  146. @Override

  147. public JestResult health() {

  148. Health health = new Health.Builder().build();

  149. JestResult result = null ;

  150. try {

  151. result = esConfig.getClient().execute(health);

  152. log.info("health == " + result.getJsonString());

  153. } catch (IOException e) {

  154. e.printStackTrace();

  155. }

  156. return result ;

  157. }

  158.  
  159. @Override

  160. public JestResult nodesStats() {

  161. NodesStats nodesStats = new NodesStats.Builder().build();

  162. JestResult result = null ;

  163. try {

  164. result = esConfig.getClient().execute(nodesStats);

  165. log.info("nodesStats == " + result.getJsonString());

  166. } catch (IOException e) {

  167. e.printStackTrace();

  168. }

  169. return result ;

  170. }

  171.  
  172. @Override

  173. public JestResult updateDocument(String script , String index, String type, String id) {

  174. /*String script = "{" +

  175. " \"doc\" : {" +

  176. " \"title\" : \""+article.getTitle()+"\"," +

  177. " \"content\" : \""+article.getContent()+"\"," +

  178. " \"author\" : \""+article.getAuthor()+"\"," +

  179. " \"source\" : \""+article.getSource()+"\"," +

  180. " \"url\" : \""+article.getUrl()+"\"," +

  181. " \"pubdate\" : \""+new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(article.getPubdate())+"\"" +

  182. " }" +

  183. "}";*/

  184. Update update = new Update.Builder(script).index(index).type(type).id(id).build();

  185. JestResult result = null ;

  186. try {

  187. result = esConfig.getClient().execute(update);

  188. log.info("updateDocument == " + result.getJsonString());

  189. } catch (IOException e) {

  190. e.printStackTrace();

  191. }

  192. return result ;

  193. }

  194.  
  195. @Override

  196. public JestResult deleteDocument(String index, String type, String id) {

  197. Delete delete = new Delete.Builder(id).index(index).type(type).build();

  198. JestResult result = null ;

  199. try {

  200. result = esConfig.getClient().execute(delete);

  201. log.info("deleteDocument == " + result.getJsonString());

  202. } catch (IOException e) {

  203. e.printStackTrace();

  204. }

  205. return result;

  206. }

  207.  
  208. @Override

  209. public JestResult deleteDocumentByQuery(String index, String type, String params) {

  210.  
  211. DeleteByQuery db = new DeleteByQuery.Builder(params)

  212. .addIndex(index)

  213. .addType(type)

  214. .build();

  215.  
  216. JestResult result = null ;

  217. try {

  218. result = esConfig.getClient().execute(db);

  219. log.info("deleteDocument == " + result.getJsonString());

  220. } catch (IOException e) {

  221. e.printStackTrace();

  222. }

  223. return result;

  224. }

  225.  
  226.  
  227. @Override

  228. public <T> JestResult getDocument(T object , String index, String type, String id) {

  229. Get get = new Get.Builder(index, id).type(type).build();

  230. JestResult result = null ;

  231. try {

  232. result = esConfig.getClient().execute(get);

  233. T o = (T) result.getSourceAsObject(object.getClass());

  234. for (Method method : o.getClass().getMethods()) {

  235. log.info("getDocument == " + method.getName());

  236. }

  237. } catch (IOException e) {

  238. e.printStackTrace();

  239. }

  240. return result;

  241.  
  242. }

  243.  
  244. @Override

  245. public List<Suggestion> suggest() {

  246. String suggestionName = "my-suggestion";

  247. Suggest suggest = new Suggest.Builder("{" +

  248. " \"" + suggestionName + "\" : {" +

  249. " \"text\" : \"the amsterdma meetpu\"," +

  250. " \"term\" : {" +

  251. " \"field\" : \"body\"" +

  252. " }" +

  253. " }" +

  254. "}").build();

  255. SuggestResult suggestResult = null ;

  256. List<SuggestResult.Suggestion> suggestionList = null ;

  257. try {

  258. suggestResult = esConfig.getClient().execute(suggest);

  259. log.info("suggestResult.isSucceeded() == " + suggestResult.isSucceeded());

  260. suggestionList = suggestResult.getSuggestions(suggestionName);

  261. log.info("suggestionList.size() == " + suggestionList.size());

  262. for(SuggestResult.Suggestion suggestion:suggestionList){

  263. System.out.println(suggestion.text);

  264. }

  265. } catch (IOException e) {

  266. e.printStackTrace();

  267. }

  268. return suggestionList ;

  269. }

  270.  
  271. @Override

  272. public <T> List<Hit<T, Void>> searchAll(String index , T o) {

  273. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

  274. searchSourceBuilder.query(QueryBuilders.matchAllQuery());

  275. Search search = new Search.Builder(searchSourceBuilder.toString())

  276. .addIndex(index)

  277. .build();

  278. SearchResult result = null ;

  279. List<?> hits = null ;

  280. try {

  281. result = esConfig.getClient().execute(search);

  282. System.out.println("本次查询共查到:"+result.getTotal()+"个关键字!");

  283. log.info("本次查询共查到:"+result.getTotal()+"个关键字!");

  284. hits = result.getHits(o.getClass());

  285. } catch (IOException e) {

  286. e.printStackTrace();

  287. }

  288. return (List<Hit<T, Void>>) hits ;

  289. }

  290.  
  291. @Override

  292. public <T> List<Hit<T, Void>> createSearch(String keyWord , String type , T o , String... fields) {

  293. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

  294. searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyWord));

  295. HighlightBuilder highlightBuilder = new HighlightBuilder();

  296. for(String field : fields){

  297. highlightBuilder.field(field);//高亮field

  298. }

  299. highlightBuilder.preTags("<em>").postTags("</em>");//高亮标签

  300. highlightBuilder.fragmentSize(200);//高亮内容长度

  301. searchSourceBuilder.highlighter(highlightBuilder);

  302. Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(type).build();

  303. SearchResult result = null ;

  304. List<?> hits = null ;

  305. try {

  306. result = esConfig.getClient().execute(search);

  307. System.out.println("本次查询共查到:"+result.getTotal()+"个结果!");

  308.  
  309. hits = result.getHits(o.getClass());

  310.  
  311. } catch (IOException e) {

  312. e.printStackTrace();

  313. }

  314. return (List<Hit<T, Void>>) hits ;

  315. }

  316.  
  317. @Override

  318. public <T> void bulkIndex(String index, String type , T o) {

  319. Bulk bulk = new Bulk.Builder()

  320. .defaultIndex(index)

  321. .defaultType(type)

  322. .addAction(Arrays.asList(

  323. new Index.Builder(o).build()

  324. )).build();

  325. try {

  326. esConfig.getClient().execute(bulk);

  327. } catch (IOException e) {

  328. e.printStackTrace();

  329. }

  330. }

  331.  
  332. @Override

  333. public <T> JestResult createIndex(T o, String index, String type) {

  334. Index index1 = new Index.Builder(o).index(index).type(type).build();

  335. JestResult jestResult = null ;

  336. try {

  337. jestResult = esConfig.getClient().execute(index1);

  338. } catch (IOException e) {

  339. e.printStackTrace();

  340. }

  341. return jestResult;

  342. }

  343.  
  344. @Override

  345. public JsonObject searchEvent(String param) {

  346. JsonObject returnData = new JsonParser().parse(param).getAsJsonObject();

  347. Search search = new Search.Builder(returnData.toString()).addType("event").addIndex("pi").build();

  348.  
  349. // Gson gs = new Gson();

  350. // System.out.println("输入参数为:" + "\n" + gs.toJson(search));

  351.  
  352. SearchResult result = null ;

  353. try {

  354. result = esConfig.getClient().execute(search);

  355. // System.out.println("\n" + gs.toJson(result.getJsonObject()) + "\n" );

  356. // System.out.println("本次查询共查到:" + "\n" +result.getTotal()+"个结果!");

  357. } catch (IOException e) {

  358. e.printStackTrace();

  359. }

  360. return result.getJsonObject();

  361. }

  362.  
  363. }

project_servlet.xml

 
  1. <!-- es连接配置 -->

  2. <bean id="esConfig" class="com.mdl.monitor.init.InitElasticSearchConfig" >

  3. <constructor-arg index="0" value="${elasticUrl}"/>

  4. </bean>

scroll分页

 
  1. @Override

  2. public JsonObject searchEventHistogramByScroll(String scrollId) {

  3. SearchScroll scroll = new SearchScroll.Builder(scrollId, "1m").build();

  4. JestResult result = null ;

  5. try {

  6. result = esConfig.getClient().execute(scroll);

  7. } catch (IOException e) {

  8. e.printStackTrace();

  9. }

  10. return result.getJsonObject();

  11. }

  12.  
  13. @Override

  14. public JsonObject searchInitEventHistogram(String param) {

  15. JsonObject returnData = new JsonParser().parse(param).getAsJsonObject();

  16. Search search = new Search.Builder(returnData.toString())

  17. .addIndex("pi")

  18. .addType("event")

  19. .setParameter(Parameters.SCROLL, "1m")

  20. .build();

  21.  
  22. JestResult result = null;

  23.  
  24. try {

  25. result = esConfig.getClient().execute(search);

  26. } catch (IOException e) {

  27. e.printStackTrace();

  28. }

  29. return result.getJsonObject();

  30. }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值