1. 程式人生 > >【轉】Elasticsearch Java Rest Client 指南

【轉】Elasticsearch Java Rest Client 指南

sta eve oat bubuko 增刪改查 cli for 在一起 min

原文地址:https://www.jianshu.com/p/d2c8326e8fa3

仔細看了下,5.6版本的RestHighLevelClient就這麽些API,有興趣的朋友可以去看看源碼:

技術分享圖片

以上包含了基本的增刪改查和批量操作

我翻了一下官方文檔,涼涼。確實像官方文檔說的那樣,需要完善。雖然是High Level的Client,但是東西少的可憐。
增(index)刪(delete)改(update)查(get)操作都是和Index,type,id嚴格綁定的。
不能跨Index操作

目前幾乎所有的High Level Rest Clent的中文介紹全部是照搬ES的文檔啊。我懶得抄,而且我司用的Elasticsearch 5.6

技術分享圖片

技術分享圖片 API少的可憐

明顯特性比版本6少了很多。所以,我倒是想填這個坑,但是太大了。還是拉倒吧。強烈建議直接去翻官方文檔,這個API版本不同版本的差別很大,一定去看自己使用的版本!現有的中文博客參考價值有限。包括本篇。

  • Java High Level REST Client

  • Document APIs

0x1 基本增刪改查

  • 第一步創建高級Client
RestClient restClient = RestClient
            .builder(new HttpHost("localhost", 9200, "http"))
            .build();

RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient);
  • 一次演示增刪改查
//增, source 裏對象創建方式可以是JSON字符串,或者Map,或者XContentBuilder 對象
IndexRequest indexRequest = new IndexRequest("指定index", "指定type", "指定ID") .source(builder);
highLevelClient.index(indexRequest);

//刪
DeleteRequest deleteRequest = new DeleteRequest("指定index", "指定type", "指定ID");
highLevelClient.delete(deleteRequest);

//改, source 裏對象創建方式可以是JSON字符串,或者Map,或者XContentBuilder 對象
UpdateRequest updateRequest = new UpdateRequest("指定index", "指定type", "指定ID").doc(builder);
highLevelClient.update(updateRequest);

//查
GetRequest getRequest = new GetRequest("指定index", "指定type", "指定ID");
highLevelClient.get(getRequest);

  • 以上四個方法都有一個***Async的方法是異步回調的,只需添加ActionListener對象即可
  • Get查詢不是唯一的查詢方法,還有SearchRequest等, 但是這個GetRequest只支持單Index操作
  • Get操作支持限定查詢的字段,傳入fetchSourceContext對象即可
  • Update 操作演示的並不是全量替換,而是和現有文檔作合並,除了doc操作還有使用Groovy script操作。
  • upsert類似update操作,不過如果文檔不存在會作為新的doc存入ES

0x2 Bulk批量操作

其實就是把一大堆IndexRequest, UpdateRequest, DeleteRequest操作放在一起。
所以缺點就是必須指定Index,否則操作沒戲。
簡單示例

BulkRequest request = new BulkRequest();
request.add(new IndexRequest("指定index", "指定type", "指定ID_1").source(XContentType.JSON,"field", "foo"));
request.add(new DeleteRequest("指定index", "指定type", "指定ID_2"));
request.add(new UpdateRequest("指定index", "指定type", "指定ID_3") .doc(XContentType.JSON,"other", "test"));

BulkResponse bulkResponse = client.bulk(request);

for (BulkItemResponse bulkItemResponse : bulkResponse) {
    if (bulkItemResponse.isFailed()) {
        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
        continue;
    }
    DocWriteResponse itemResponse = bulkItemResponse.getResponse();
    if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX
            || bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) {
        IndexResponse indexResponse = (IndexResponse) itemResponse;
    } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) {
        UpdateResponse updateResponse = (UpdateResponse) itemResponse;
    } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) {
        DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
    }
}

0x3 SearchRequest高級查詢

支持多文檔查詢、聚合操作。可以完全取代GetRequest。

// 創建
SearchRequest searchRequest = new SearchRequest(); 
SearchSourceBuilder builder = new SearchSourceBuilder(); 
searchSourceBuilder.query(xxxQuery); 
searchRequest.source(builder);

可以在創建的時候指定index,SearchRequest searchRequest = new SearchRequest("some_index*");,支持帶*號的模糊匹配

當然,這並不是最厲害的地方,最NB的地方是,支持QueryBuilder,兼容之前TransportClient的代碼

  • 我自己寫的跨Index模糊查詢
        SearchRequest searchRequest = new SearchRequest("gdp_tops*");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("city", "北京市"));
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);
        try {
            SearchResponse response = highLevelClient.search(searchRequest);
            Arrays.stream(response.getHits().getHits())
                    .forEach(i -> {
                        System.out.println(i.getIndex());
                        System.out.println(i.getSource());
                        System.out.println(i.getType());

                    });
            System.out.println(response.getHits().totalHits);
        } catch (IOException e) {
            e.printStackTrace();
        }
  • 官方給出的聚合查詢
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_company")
        .field("company.keyword");
aggregation.subAggregation(AggregationBuilders.avg("average_age")
        .field("age"));
searchSourceBuilder.aggregation(aggregation);
  • 當然還支持異步查詢
    官方示例
client.searchAsync(searchRequest, new ActionListener<SearchResponse>() {
    @Override
    public void onResponse(SearchResponse searchResponse) {
        
    }

    @Override
    public void onFailure(Exception e) {
        
    }
});
  • 查詢結果處理
    查詢結束後會得到一個SearchResponse對象,可以拿到查詢狀態,消耗時間,查詢到的總條目數等參數,具體結果操作
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// 結果的Index
    String index = hit.getIndex();
// 結果的type
    String type = hit.getType();
// 結果的ID
    String id = hit.getId();
// 結果的評分
    float score = hit.getScore();
// 查詢的結果 JSON字符串形式
    String sourceAsString = hit.getSourceAsString();
// 查詢的結果 Map的形式
    Map<String, Object> sourceAsMap = hit.getSourceAsMap();
// Document的title
    String documentTitle = (String) sourceAsMap.get("title");
// 結果中的某個List
    List<Object> users = (List<Object>) sourceAsMap.get("user");
// 結果中的某個Map
    Map<String, Object> innerObject = (Map<String, Object>) sourceAsMap.get("innerObject");
}
  • 聚合查詢
    前面演示的是正常查詢,聚合查詢官方文檔也有展示
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_company")
        .field("company.keyword");
aggregation.subAggregation(AggregationBuilders.avg("average_age")
        .field("age"));
searchSourceBuilder.aggregation(aggregation);

和query查詢一樣,searchSourceBuilder使用aggregation()方法即可
查詢到的結果處理也跟普通查詢類似,處理一下Bucket就可以展示到接口了

Aggregations aggregations = searchResponse.getAggregations();
Terms byCompanyAggregation = aggregations.get("by_company"); 
Bucket elasticBucket = byCompanyAggregation.getBucketByKey("Elastic"); 
Avg averageAge = elasticBucket.getAggregations().get("average_age"); 
double avg = averageAge.getValue();

0x4 分頁和滾動搜索

有時候結果需要分頁查詢,推薦使用searchSourceBuilder

sourceBuilder.from(0); 
sourceBuilder.size(5);

有時候需要查詢的數據太多,可以考慮使用SearchRequest.scroll()方法拿到scrollId;之後再使用SearchScrollRequest
其用法如下:

SearchRequest searchRequest = new SearchRequest("posts");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(matchQuery("title", "Elasticsearch"));
searchSourceBuilder.size(size); 
searchRequest.source(searchSourceBuilder);
searchRequest.scroll(TimeValue.timeValueMinutes(1L)); 
SearchResponse searchResponse = client.search(searchRequest);
String scrollId = searchResponse.getScrollId(); 
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); 
scrollRequest.scroll(TimeValue.timeValueSeconds(30));
SearchResponse searchScrollResponse = client.searchScroll(scrollRequest);
scrollId = searchScrollResponse.getScrollId();  
hits = searchScrollResponse.getHits(); 
assertEquals(3, hits.getTotalHits());
assertEquals(1, hits.getHits().length);
assertNotNull(scrollId);

Scroll查詢的使用場景是密集且前後有關聯的查詢。如果只是一般的分頁,可以使用size from來處理

【轉】Elasticsearch Java Rest Client 指南