ElasticSearch Java Client: TransportClient 查询操作

ElasticSearch 5.6版本之前,均使用TransportClient Java Client,5.6之后建议使用RestHighLevelClient,可参考ElasticSearch Java Client: RestHighLevelClient 查询操作

 TransportClient client = new PreBuiltTransportClient(Settings.builder()
                    .put("cluster.name", "net_device_log_cluster").build())
                    //这里的端口是9300,而不是rest请求的9200端口
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.44.100.116"), 9300))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.44.100.141"), 9300));
 BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
 boolQuery.must(QueryBuilders.wildcardQuery("host", "10.229.208.*"));
 boolQuery.mustNot(QueryBuilders.matchQuery("message", "DISPLAY_CMDRECORD"));
 boolQuery.mustNot(QueryBuilders.matchQuery("message", "SUPPRESS_LOG"));
 boolQuery.filter(QueryBuilders.rangeQuery("@timestamp").gte(start).lte(end));
 String[] includeFields = new String[] {"message", "@timestamp"};
 String[] excludeFields = new String[] {};
 SearchResponse searchResponse = client.prepareSearch(index).setTypes("network")
                .setQuery(boolQuery).setFetchSource(includeFields, excludeFields).get();
 SearchHits hits = searchResponse.getHits();
 SearchHit[] searchHits = hits.getHits();
 for(SearchHit hit : searchHits) {
      System.out.println(hit.getSourceAsString());
  }

注意:
1 ElasticSearch的版本和Java Client的版本要匹配

Get请求查看ElasticSearch版本和cluster_name
postman get: http://host_ip:9200
{
    "name": "net-node-3",
    "cluster_name": "net_device_log_cluster",
    "cluster_uuid": "eQoCPBWNRSCJcUVISB9jpw",
    "version": {
        "number": "5.5.1",
        "build_hash": "19c13d0",
        "build_date": "2017-07-18T20:44:24.823Z",
        "build_snapshot": false,
        "lucene_version": "6.6.0"
    },
    "tagline": "You Know, for Search"
}

2 在使用SpringBoot框架的后台中,一定要通过properties方式指定ElasticSearch的版本,否则会加载SpringBoot默认的版本,有可能报错


        1.8
        5.0.0


    
        org.elasticsearch.client
        transport
    

你可能感兴趣的:(ElasticSearch Java Client: TransportClient 查询操作)