Elasticsearch Java client

ES Client 简介

ES是一个服务,采用C/S结构

ES支持的客户端连接方式

  • REST API 端口9200

    这种连接方式对应于RESTful style API这一层,这种客户端的连接方式是RESTful风格的,使用http的方式进行连接

  • Transport 连接 端口 9300

    这种连接方式对应于Transport这一层,这种客户端连接方式是直接连接ES的节点,使用TCP的方式进行连接

参考官网

https://www.elastic.co/guide/en/elasticsearch/client/index.html

Java REST Client介绍

maven

		<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>6.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.2.2</version>
        </dependency>

初始化

RestHighLevelClient client = new RestHighLevelClient(
                 RestClient.builder(new HttpHost("172.16.20.110", 9200, "http"),
                         new HttpHost("172.16.20.110", 9201, "http")));
                         //172.16.20.110  localhost

API及用法示例

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-supported-apis.html

使用

InitDemo

 /*
  * Copyright 2018 tuhu.cn All right reserved. This software is the
  * confidential and proprietary information of tuhu.cn ("Confidential
  * Information"). You shall not disclose such Confidential Information and shall
  * use it only in accordance with the terms of the license agreement you entered
  * into with Tuhu.cn
  */
 package com.example.demo.util;

 import org.apache.http.HttpHost;
 import org.elasticsearch.client.RestClient;
 import org.elasticsearch.client.RestHighLevelClient;

 /**
  * @auther chendesheng
  * @date 2018/12/19
  */
 public class InitDemo {
     public static RestHighLevelClient getClient() {
        
         RestHighLevelClient client = new RestHighLevelClient(
                 RestClient.builder(new HttpHost("172.16.20.110", 9200, "http"),
                         new HttpHost("172.16.20.110", 9201, "http")));
                         //172.16.20.110  localhost
         return client;
     }
    
 }

QueryService

 package com.example.demo.service;

 import java.util.List;
 import java.util.Map;

 /**
  * @auther chendesheng
  * @date 2018/12/20
  */
 public interface QueryService {
     
     List<Map<String, Object>> queryListByRequestid(String es,String requestid);
    

 }

QueryServiceImpl


 package com.example.demo.service.impl;
 
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import com.example.demo.service.QueryService;
 import com.example.demo.util.InitDemo;
 import org.elasticsearch.action.search.SearchRequest;
 import org.elasticsearch.action.search.SearchResponse;
 import org.elasticsearch.action.search.ShardSearchFailure;
 import org.elasticsearch.client.RestHighLevelClient;
 import org.elasticsearch.common.unit.TimeValue;
 import org.elasticsearch.index.query.QueryBuilders;
 import org.elasticsearch.rest.RestStatus;
 import org.elasticsearch.search.SearchHit;
 import org.elasticsearch.search.SearchHits;
 import org.elasticsearch.search.builder.SearchSourceBuilder;
 import org.springframework.stereotype.Service;

 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;


 /**
  * @auther chendesheng
  * @date 2018/12/20
  */
 @Service
 public class QueryServiceImpl implements QueryService {
     private static Logger logger = LogManager.getRootLogger();
    
     @Override
     public List<Map<String, Object>> queryListByRequestid(String es,String requestid) {
        
         List<Map<String, Object>> list = new ArrayList<>();
         
         try (RestHighLevelClient client = InitDemo.getClient();) {
        
             // 1、创建search请求
             //SearchRequest searchRequest = new SearchRequest();
             SearchRequest searchRequest = new SearchRequest(es);
             searchRequest.types("doc");
        
             // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
             SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        
             //构造QueryBuilder
            /*QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("user", "kimchy")
                    .fuzziness(Fuzziness.AUTO)
                    .prefixLength(3)
                    .maxExpansions(10);
            sourceBuilder.query(matchQueryBuilder);*/
        
             sourceBuilder.query(QueryBuilders.termQuery("requestid.keyword", requestid));
             sourceBuilder.from(0);
             sourceBuilder.size(1000);
             sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        
             //是否返回_source字段
             //sourceBuilder.fetchSource(false);
        
             //设置返回哪些字段
            /*String[] includeFields = new String[] {"title", "user", "innerObject.*"};
            String[] excludeFields = new String[] {"_type"};
            sourceBuilder.fetchSource(includeFields, excludeFields);*/
        
            
        
             // 设置返回 profile 
             //sourceBuilder.profile(true);
        
             //将请求体加入到请求中
             searchRequest.source(sourceBuilder);
        
             
             //3、发送请求        
             SearchResponse searchResponse = client.search(searchRequest);
        
        
             //4、处理响应
             //搜索结果状态信息
             RestStatus status = searchResponse.status();
             TimeValue took = searchResponse.getTook();
             Boolean terminatedEarly = searchResponse.isTerminatedEarly();
             boolean timedOut = searchResponse.isTimedOut();
        
             //分片搜索情况
             int totalShards = searchResponse.getTotalShards();
             int successfulShards = searchResponse.getSuccessfulShards();
             int failedShards = searchResponse.getFailedShards();
             for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
                 // failures should be handled here
             }
        
             //处理搜索命中文档结果
             SearchHits hits = searchResponse.getHits();
        
             long totalHits = hits.getTotalHits();
             float maxScore = hits.getMaxScore();
        
             SearchHit[] searchHits = hits.getHits();
             logger.info("总数:"+searchHits.length);
             
             for (SearchHit hit : searchHits) {
                 // do something with the SearchHit
            
                 String index = hit.getIndex();
                 String type = hit.getType();
                 String id = hit.getId();
                 float score = hit.getScore();
            
                 //取_source字段值
                 String sourceAsString = hit.getSourceAsString(); //取成json串
                 Map<String, Object> sourceAsMap = hit.getSourceAsMap(); // 取成map对象
                 list.add(sourceAsMap);
                 //从map中取字段值
                /*
                String documentTitle = (String) sourceAsMap.get("title"); 
                List<Object> users = (List<Object>) sourceAsMap.get("user");
                Map<String, Object> innerObject = (Map<String, Object>) sourceAsMap.get("innerObject");
                */
                 logger.info("index:" + index + "  type:" + type + "  id:" + id);
                 logger.info(sourceAsString);
                 
             }
        
         } catch (IOException e) {
             logger.error(e);
         }
         
         return list;
     }
    
 }

QueryContronller


 package com.example.demo.controller;

 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.example.demo.service.QueryService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RestController;
 import java.util.List;
 import java.util.Map;

 /**
  * @auther chendesheng
  * @date 2018/12/20
  */
 @RestController
 public class QueryController {
     
     @Autowired
     QueryService queryService;
    
     /**
      * 查询 logstash-serviceperformance-*
      * 查询 logstash-servicelog-*
      * @param requestid
      * @return 
      */
     @PostMapping("/queryByRequestid")
     public JSONObject queryList4(String requestid){
         JSONObject jsonObject = new JSONObject();
         JSONArray jsonArray = null;
         JSONArray jsonArray2 = null;
         try {
             List<Map<String, Object>> list = queryService.queryListByRequestid("logstash-serviceperformance-*",requestid);
             List<Map<String, Object>> list2 = queryService.queryListByRequestid("logstash-servicelog-*",requestid);
             jsonArray = (JSONArray) JSONArray .toJSON(list);
             jsonArray2 = (JSONArray) JSONArray .toJSON(list2);
             jsonObject.put("logstash_serviceperformance-*:",jsonArray);
             jsonObject.put("logstash-servicelog-*:",jsonArray2);
         }catch (Exception e){
             e.printStackTrace();
             jsonObject.put("msgcode:",500);
         }
         return jsonObject;
     }
 }
坚持原创技术分享,您的支持将鼓励我继续创作!