2020-10-27

1、获取ElasticSearch client对象

 
  1. public Client getEsClient(){

  2. Client client = null;

  3. try{

  4. Settings settings = ImmutableSettings.settingsBuilder()

  5. .put("client.transport.sniff", true) //自动嗅探整个ES集群节点

  6. .put("client", true)

  7. .put("data",false)

  8. .put("cluster.name","elasticsearch") //设置集群名字

  9. .put("number_of_shards", 2) //2个主分片

  10. .put("index.refresh_interval", "5s") //每5秒提交一次数据,类似oracle中的commit

  11. .build();

  12. client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("hostName", 9200));

  13. }catch(Exception ex){

  14. ex.printStackTrace();

  15. }

  16. return client;

  17. }

2、查询List方法

 
  1. List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

  2. Client client = null;

  3. try{

  4. //获取Elasticsearch client对象

  5. client = getEsClient();

  6. //设置查询条件(类似sql中 eventid = eventid )

  7. QueryBuilder qb = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("eventid", eventid));

  8. // 设置ES中 indexName 和 indexType,以及QueryBuilders 对象

  9. SearchRequestBuilder requestBuilder = client.prepareSearch(EventBean.indexName)

  10. .setTypes(EventBean.indexType)

  11. .setQuery(qb);

  12. //执行查询 (可以设置排序、分页)

  13. SearchResponse actionGet = requestBuilder.addSort(SortBuilders.fieldSort("occurtime").order(SortOrder.DESC))

  14. .setFrom((pageNum-1) * pageSize)

  15. .setSize(pageNum * pageSize)

  16. .execute().actionGet();

  17. //遍历查询结果

  18. if(actionGet != null){

  19. SearchHits hits = actionGet.getHits();

  20. if(hits != null && hits.getHits() != null){

  21. Map<String, Object> hitMap = null;

  22. for (SearchHit hit : hits.getHits()){

  23. hitMap = hit.getSource();

  24. if(hitMap == null || hitMap.size() <= 0){

  25. continue;

  26. }

  27. dataList.add(hitMap );

  28. }

  29. }

  30. }

  31. }catch(Exception ex){

  32. ex.printStackTrace();

  33. }finally{

  34. //关闭client

  35. }

  36. return dataList ;

3、查询总数方法

 
  1. int rowTotal = 0;

  2. Client client = null;

  3. try{

  4. //获取Elasticsearch client对象

  5. client = getEsClient();

  6. //设置查询条件 (类似sql中 title like '%searchtext%')

  7. QueryBuilder qb = QueryBuilders.boolQuery().must(QueryBuilders.wildcardQuery("title", "*"+searchtext+"*"));

  8. // 设置ES中 indexName 和 indexType,以及QueryBuilders 对象

  9. CountRequestBuilder requestBuilder = client.prepareCount(EventBean.indexName)

  10. .setTypes(EventBean.indexType)

  11. .setQuery(qb);

  12. // 查询动作

  13. rowTotal = ConverUtils.Obj2int( requestBuilder.execute()

  14. .actionGet().getCount(), 0);

  15. }catch(Exception ex){

  16. ex.printStackTrace();

  17. }finally{

  18. //关闭client

  19. }

  20. return rowTotal;

4、添加方法

 
  1. boolean optFlag = false;

  2. Client client = null;

  3. try{

  4. //获取Elasticsearch client对象

  5. client = getEsClient();

  6. //构造请求对象

  7. BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

  8. IndexRequestBuilder indexRequestBuilder = null;

  9. //根据请求对象bodyList, 组织bulkRequestBuilder对象

  10. String indexId = "";

  11. Map<String, Object> bodyMap = null;

  12. for (int count = 0; count < bodyList.size(); count++) {

  13. bodyMap = bodyList.get(count);

  14. if (bodyMap == null) {

  15. break;

  16. }

  17. //组织索引对象id

  18. indexId = ConverUtils.Obj2Str(bodyMap.get("id"), "");

  19. indexRequestBuilder = client.prepareIndex(indexName, indexType).setId(indexId).setSource(bodyMap);

  20. bulkRequestBuilder.add(indexRequestBuilder);

  21. }

  22. //批量更新执行

  23. BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();

  24. if (bulkResponse.hasFailures()) {

  25. optFlag = false;

  26. } else {

  27. optFlag = true;

  28. }

  29. }catch(Exception ex){

  30. ex.printStackTrace();

  31. }finally{

  32. //关闭client

  33. }

  34. return optFlag ;

5、更新方法

 
  1. boolean optFlag = false;

  2. Client client = null;

  3. try{

  4. //获取Elasticsearch client对象

  5. client = getEsClient();

  6. //构造请求对象

  7. BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

  8. UpdateRequestBuilder updateRequestBuilder = null;

  9. //根据请求对象cvdMap,组织索引对象

  10. String indexId = getEsIndexId(client, ConverUtils.Obj2long(cvdMap.get("id"), 0L));

  11. //获取索引(getEsIndexId)

  12. updateRequestBuilder = client.prepareUpdate(indexName, indexType, indexId).setDoc(cvdMap);

  13. bulkRequestBuilder.add(updateRequestBuilder);

  14. //批量更新执行

  15. BulkResponse bulkResponse = bulkRequestBuilder.setRefresh(true).execute().actionGet();

  16. if (bulkResponse.hasFailures()) {

  17. optFlag = false;

  18. } else {

  19. optFlag = true;

  20. }

  21. }catch(Exception ex){

  22. ex.printStackTrace();

  23. }finally{

  24. //关闭client

  25. }

  26. return optFlag ;

6、删除方法

 
  1. boolean optFlag = false;

  2. Client client = null;

  3. try{

  4. //获取Elasticsearch client对象

  5. client = getEsClient();

  6. //根据id_array数组, 组织索引对象

  7. BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

  8. DeleteRequestBuilder deleteRequestBuilder = null;

  9. for(int i=0; i<id_array.length; i++){

  10. if(id_array[i] == null || id_array[i].trim().equals("")){

  11. continue;

  12. }

  13. //根据indexName, indexType, indexId进行删除(这里nfa_dictionary索引中ID字段值和ES自有_id值相同, 可以操作)

  14. deleteRequestBuilder = client.prepareDelete(indexName, indexType, id_array[i]);

  15. bulkRequestBuilder.add(deleteRequestBuilder.request());

  16. }

  17. //进行批量删除操作

  18. BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();

  19. if (bulkResponse.hasFailures()) {

  20. optFlag = false;

  21. }else {

  22. optFlag = true;

  23. }

  24. }catch(Exception ex){

  25. ex.printStackTrace();

  26. }finally{

  27. //关闭client

  28. }

  29. return optFlag ;

其它:

 
  1. public static void main(String[] args) throws Exception{

  2. searchmethod6();

  3. }

  4.  
  5. /**

  6. * 方法一

  7. * @throws Exception

  8. */

  9. public static void searchmethod1() throws Exception{

  10. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  11. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  12.  
  13. SearchResponse response = client.prepareSearch("movies").setTypes("movie").get();

  14. println(response);

  15. for (SearchHit searchHit: response.getHits()) {

  16. println(searchHit);

  17. }

  18. }

  19.  
  20. /**

  21. * 方法二

  22. * @throws Exception

  23. */

  24. public static void searchmethod2() throws Exception{

  25. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  26. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  27.  
  28. QueryBuilder qb1 = termQuery("user","10");

  29. // QueryBuilder qb2 = QueryBuilders.multiMatchQuery("git", "title", "content");

  30. SearchResponse response = client.prepareSearch("movies").setQuery(qb1).get();

  31. for (SearchHit searchHit: response.getHits()) {

  32. println(searchHit);

  33. }

  34. }

  35.  
  36. /**

  37. * 方法三

  38. * @throws Exception

  39. * 这个相当于之前的分页,使用的是Scroll方法

  40. */

  41. public static void searchmethod3() throws Exception{

  42. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  43. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  44. QueryBuilder qb = termQuery("user", "kimchy");

  45.  
  46. SearchResponse scrollResp = client.prepareSearch("movies")

  47. .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)

  48. .setScroll(new TimeValue(60000))

  49. .setQuery(qb)

  50. .setSize(1).get();

  51. do {

  52. for (SearchHit hit : scrollResp.getHits().getHits()) {

  53. println(hit);

  54. }

  55.  
  56.  
  57. scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();

  58. } while(scrollResp.getHits().getHits().length != 0);

  59. }

  60.  
  61.  
  62. /**

  63. * 方法四

  64. * @throws Exception

  65. */

  66. public static void searchmethod4() throws Exception{

  67. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  68. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  69.  
  70. SearchRequestBuilder srb1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("kimchy"));

  71. SearchRequestBuilder srb2 = client.prepareSearch().setQuery(QueryBuilders.matchQuery("user", "kimchy"));

  72.  
  73. MultiSearchResponse sr = client.prepareMultiSearch().add(srb1).add(srb2).get();

  74.  
  75. for (MultiSearchResponse.Item item : sr.getResponses()) {

  76. SearchResponse response = item.getResponse();

  77. for (SearchHit searchHit : response.getHits()) {

  78. println(searchHit);

  79. }

  80. }

  81. }

  82.  
  83. /**

  84. * 方法五

  85. * 这个方法先欠着,不是很懂

  86. * @throws Exception

  87. */

  88. public static void searchmethod5() throws Exception{

  89. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  90. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  91.  
  92. SearchResponse sr = client.prepareSearch()

  93. .setQuery(QueryBuilders.matchAllQuery())

  94. .addAggregation(

  95. AggregationBuilders.terms("agg1").field("field")

  96. )

  97. .addAggregation(

  98. AggregationBuilders.dateHistogram("agg2")

  99. .field("birth")

  100. .dateHistogramInterval(DateHistogramInterval.YEAR)

  101. )

  102. .get();

  103.  
  104. // Get your facet results

  105. Terms agg1 = sr.getAggregations().get("agg1");

  106. // DateHistogram agg2 = sr.getAggregations().get("agg2");

  107. }

  108.  
  109.  
  110.  
  111. /**

  112. * 方法六

  113. * 能运行,但是就是不知道为什么查询不到结果,同时感觉这种方法很鸡肋,感觉写起来很麻烦,顺便说一下这个东西好像也可以在script下配置,我测试失败,但是感觉没什么用,就不深究了。

  114. * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-template.html

  115. * @throws Exception

  116. */

  117. public static void searchmethod6() throws Exception{

  118. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)

  119. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));

  120.  
  121. Map<String, Object> json = new HashMap<>();

  122. json.put("param_gender", "1962");

  123.  
  124. SearchResponse response = new SearchTemplateRequestBuilder(client)

  125. .setScript("{\n" +

  126. " \"query\" : {\n" +

  127. " \"match\" : {\n" +

  128. " \"year\" : \"{{param_gender}}\"\n" +

  129. " }\n" +

  130. " }\n" +

  131. "}")

  132.  
  133. .setScriptType(ScriptType.INLINE)

  134. .setScriptParams(json)

  135. .setRequest(new SearchRequest())

  136. .get()

  137. .getResponse();

  138. println(response);

  139. System.out.println(response.getHits().getTotalHits());

  140. for (SearchHit searchHit : response.getHits()) {

  141. println(searchHit);

  142. }

  143.  
  144. }

  145.  
  146.  
  147.  
  148.  
  149. /**

  150. * 输出结果SearchResponse

  151. * @param response

  152. */

  153. public static void println(SearchResponse response){

  154. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");

  155. System.err.println(

  156. "getFailedShards : " + response.getFailedShards() + "\n" +

  157. "getNumReducePhases : " + response.getNumReducePhases() + "\n" +

  158. "getScrollId : " + response.getScrollId() + "\n" +

  159. "getTookInMillis : " + response.getTookInMillis() + "\n" +

  160. "getTotalShards : " + response.getTotalShards() + "\n" +

  161. "getAggregations : " + response.getAggregations() + "\n" +

  162. "getProfileResults : " + response.getProfileResults() + "\n" +

  163. "getShardFailures : " + response.getShardFailures() + "\n" +

  164. "getSuggest : " + response.getSuggest() + "\n" +

  165. "getTook : " + response.getTook() + "\n" +

  166. "isTerminatedEarly : " + response.isTerminatedEarly() + "\n" +

  167. "isTimedOut : " + response.isTimedOut() + "\n" +

  168. "remoteAddress : " + response.remoteAddress() + "\n" +

  169. "status : " + response.status() + "\n" +

  170. "getHits : " + response.getHits()

  171. );

  172. }

  173.  
  174. /**

  175. * 输出结果SearchResponse

  176. * @param response

  177. */

  178. public static void println(SearchHit searchHit){

  179. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");

  180. System.err.println(

  181. "docId : " + searchHit.docId() + "\n" +

  182. "getId : " + searchHit.getId() + "\n" +

  183. "getIndex : " + searchHit.getIndex()+ "\n" +

  184. "getScore : " + searchHit.getScore() + "\n" +

  185. "getSourceAsString : " + searchHit.getSourceAsString() + "\n" +

  186. "getType : " + searchHit.getType() + "\n" +

  187. "getVersion : " + searchHit.getVersion() + "\n" +

  188. "fieldsOrNull : " + searchHit.fieldsOrNull() + "\n" +

  189. "getExplanation : " + searchHit.getExplanation() + "\n" +

  190. "getFields : " + searchHit.getFields() + "\n" +

  191. "highlightFields : " + searchHit.highlightFields() + "\n" +

  192. "hasSource : " + searchHit.hasSource()

  193. );

  194. }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值