elastaicsearch用java RestHighLevelClient 方式(三)

maven 的pom.xml如下


    4.0.0

    com.ultrapower.es
    RestHighLevelClient
    1.0-SNAPSHOT
    
        UTF-8
        1.8
        1.8
    
    
        
            org.elasticsearch
            elasticsearch
            6.1.1
        
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            6.1.1
        
        
            org.apache.logging.log4j
            log4j-core
            2.8.2
        
        
            org.apache.logging.log4j
            log4j-api
            2.8.2
        

        
            com.google.code.gson
            gson
            2.8.1
        
        
            junit
            junit
            4.10
        

    

客户端java语言

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

/**
 * @author xiefg
 * @create 2018-01-05 14:10
 * @desc
 **/
public class RestClientFactory {
    private static  String HOST="192.168.170.69";
    private static  int PORT = 9200;
    private static final String SCHEMA = "http";
    private static final int CONNECT_TIME_OUT = 1000;
    private static final int SOCKET_TIME_OUT = 30000;
    private static final int CONNECTION_REQUEST_TIME_OUT = 500;

    private static final int MAX_CONNECT_NUM = 100;
    private static final int MAX_CONNECT_PER_ROUTE = 100;

    private static HttpHost HTTP_HOST=null;
    private static boolean uniqueConnectTimeConfig = false;
    private static boolean uniqueConnectNumConfig = true;
    private static RestClientBuilder builder;
    private static RestClient restClient;
    private static RestHighLevelClient restHighLevelClient;

    public static void init(){
       // HOST = Configuration.getProperty("esHost");
       // PORT = Integer.parseInt(Configuration.getProperty("esPort"));
        if(HTTP_HOST==null){
            HTTP_HOST=new HttpHost(HOST,PORT,SCHEMA);
        }
        builder = RestClient.builder(HTTP_HOST);
        if(uniqueConnectTimeConfig){
            setConnectTimeOutConfig();
        }
        if(uniqueConnectNumConfig){
            setMutiConnectConfig();
        }
        restClient = builder.build();
        restHighLevelClient = new RestHighLevelClient(builder);
    }

    /**
     *     主要关于异步httpclient的连接延时配置
     */

    public static void setConnectTimeOutConfig(){
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(CONNECT_TIME_OUT);
            requestConfigBuilder.setSocketTimeout(SOCKET_TIME_OUT);
            requestConfigBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIME_OUT);
            return requestConfigBuilder;
        });
    }
    /**
     *    主要关于异步httpclient的连接数配置
     */
    public static void setMutiConnectConfig(){
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(MAX_CONNECT_NUM);
            httpClientBuilder.setMaxConnPerRoute(MAX_CONNECT_PER_ROUTE);
            return httpClientBuilder;
        });
    }

    public static RestClient getClient(){
        return restClient;
    }

    public static RestHighLevelClient getHighLevelClient(){
        if(restHighLevelClient==null){
            init();
        }
        return restHighLevelClient;
    }

    public static void close() {
        if (restHighLevelClient != null) {
            try {
                restHighLevelClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xiefg
 * @create 2018-01-05 9:38
 * @desc
 **/
public class EsIndexDemo {

    /**
     *  同步获取操作结果
      */
    public static IndexResponse postRequest(String index, String type, String id, String jsonSource)
            throws Exception {
        // 构建请求
        IndexRequest request = new IndexRequest(index, type, id);
        // 将保存数据以JSON格式关联到请求
        request.source(jsonSource, XContentType.JSON);
        // Java客户端发起保存数据请求
        IndexResponse response = RestClientFactory.getHighLevelClient().index(request);
        // 等待结果
        System.out.println(response);
        return response;
    }
    /**
     * @param keyword1 关键字1
     * @param keyword2 关键字2
     * @param startDate 起始时间
     * @param endDate 终止时间
     *
     **/
    public  static SearchResponse pageQueryRequest(String keyword1, String keyword2, String startDate, String endDate,
                                              int start, int size){
        RestHighLevelClient client = RestClientFactory.getHighLevelClient();

        // 这个sourcebuilder就类似于查询语句中最外层的部分。包括查询分页的起始,
        // 查询语句的核心,查询结果的排序,查询结果截取部分返回等一系列配置
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 结果开始处
        sourceBuilder.from(start);
        // 查询结果终止处
        sourceBuilder.size(size);
        // 查询的等待时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        MatchQueryBuilder matchbuilder;
        matchbuilder = QueryBuilders.matchQuery("message", keyword1+" "+keyword2);
        // 同时满足两个关键字
        matchbuilder.operator(Operator.AND);
        // 查询在时间区间范围内的结果
        RangeQueryBuilder rangbuilder = QueryBuilders.rangeQuery("date");
        if(!"".equals(startDate)){
            rangbuilder.gte(startDate);
        }
        if(!"".equals(endDate)){
            rangbuilder.lte(endDate);
        }
        // 等同于bool,将两个查询合并
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.must(matchbuilder);
        boolBuilder.must(rangbuilder);
        // 排序
        FieldSortBuilder fsb = SortBuilders.fieldSort("date");
        fsb.order(SortOrder.DESC);
        sourceBuilder.sort(fsb);

        sourceBuilder.query(boolBuilder);
        //System.out.println(sourceBuilder);
        SearchRequest searchRequest = new SearchRequest("request");
        searchRequest.types("doc");
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest);
            SearchHits hits= response.getHits();
            int totalRecordNum= (int) hits.getTotalHits();
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
                    .create();
            for (SearchHit searchHit : hits) {
                Map source = searchHit.getSourceAsMap();
                Object entity =gson.fromJson(gson.toJson(source),User.class);
                System.out.println(entity);
            }


            client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return response;
    }

    public static void main(String[] args) {
        String jsonString = "{" + "\"user\":\"xiefg\"," + "\"date\":\"2018-01-12\","
                + "\"message\":\"trying out Elasticsearch\"" + "}";
        try {
            for (int i=0;i<30;i++){
                postRequest("request", "doc", UUID.randomUUID()+"", jsonString);
            }
            RestClientFactory.close();
   
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

/**
 * @author xiefg
 * @create 2018-01-05 18:09
 * @desc
 **/
public class User {
    private String  user;
    private String   date;
    private String  message;




    public String getUser() {
        return user;
    }


    public void setUser(String user) {
        this.user = user;
    }


    public String getMessage() {
        return message;
    }


    public void setMessage(String message) {
        this.message = message;
    }


    public String getDate() {
        return date;
    }


    public void setDate(String date) {
        this.date = date;
    }


    @Override
    public String toString() {
        return "User{" +
                "user='" + user + '\'' +
                ", date='" + date + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
import org.junit.Test;


/**
 * @author xiefg
 * @create 2018-01-05 10:45
 * @desc
 **/


public class ESTest {


     @Test
    public void queryKeyWorld(){
         EsIndexDemo.pageQueryRequest("trying","out","2018-01-12","2018-01-12",0,9);
     }
}

你可能感兴趣的:(elasticsearch)