Elasticsearch Java Client 版本区别及起步(5.X 和6.X)

目前ElasticSearch版本最常用的应该时5.X 和6.X,这两个版本中都存在两种客户端:

Elasticsearch Java Client 版本区别及起步(5.X 和6.X)_第1张图片

简单总结:

1,如果服务端是5.6以下的,选择相同版本的TransportClient,避免一些API服务端不支持

2,如果服务端是5.6以上的,选择相同版本的RestClient

TransportClient起步:

5.6及之前的版本:

// on startup

Client client = TransportClient.builder().build()
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));

// on shutdown

client.close();

6.0及之后的版本

// on startup

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host1"), 9300))
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host2"), 9300));

// on shutdown

client.close();

TransportClient发送搜索请求:

SearchResponse response = client.prepareSearch("index1", "index2")
        .setTypes("type1", "type2")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(QueryBuilders.termQuery("multi", "test"))                 // Query
        .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
        .setFrom(0).setSize(60).setExplain(true)
        .get();

 

HttpClient起步:

//  Java Low Level REST Client
RestClient lowLevelRestClient = RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();

// Java High Level REST Client
RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient);

HttpClient发送搜索请求:

SearchRequest searchRequest = new SearchRequest(); searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);

参考:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.2/index.html

转载于:https://www.cnblogs.com/lishaojun/p/10963657.html

你可能感兴趣的:(Elasticsearch Java Client 版本区别及起步(5.X 和6.X))