es5.x共通クエリー(javaAPI)

33490 ワード

筆者のすべての文章はhhbbzの個人ブログに最初に発表された.
概要
JAva Elasticクライアント基本使用
jarの導入
   compile 'org.elasticsearch:elasticsearch:5.5.0'

   compile 'org.elasticsearch.client:transport:5.5.0

クライアントの基本使用
クライアントを取得
Settings settings = Settings.builder().put("cluster.name", "hbz-6-test").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

リソースを閉じる
client.close();
          

get指定index type idのデータを得る
public static void prepareGet(TransportClient client) throws Exception {
        GetResponse response = client.prepareGet("mytest", "test", "p1").get();
        System.out.println(response);
}

output:
{
    "_index":"mytest",
    "_type":"test",
    "_id":"p1",
    "_version":1,
    "found":true,
    "_source":{
        "name":"mac Book    ",
        "price":1233,
        "description":"     ",
        "cats":[
            "3c",
            "computer"
        ]
    }
}


Insertデータの追加
public static void insert(TransportClient client) throws Exception {
        Map resource = new HashMap<>();
        resource.put("name","mac Note");
        resource.put("price",8877);
        resource.put("description","mac Note   ");
        IndexRequestBuilder index = client.prepareIndex("mytest", "test");

        IndexResponse insertResponse = index.setSource(resource).execute().get();

        System.out.println(insertResponse);
}


output:
    IndexResponse[index=mytest,type=test,id=AV8CZmTgGnilLCUrybiV,version=1,result=created
    ,shards={"total":2,"successful":1,"failed":0}]

deleteデータの削除
public static void delete(TransportClient client) throws Exception{
        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchQuery("name", "mac")) //  
                .source("mytest") //index
                .get();


       long deleted = response.getDeleted();
       System.out.println("    : "+deleted);

}


updateデータの変更
public static void update(TransportClient client) throws Exception{

        Map data = new HashMap<>();
        data.put("name","new mac node");

        UpdateRequest updateRequest =  new UpdateRequest();
        updateRequest.index("mytest");
        updateRequest.type("test");
        updateRequest.id("AV8CfcSLGnilLCUryoEl");

        updateRequest.doc(data);

        UpdateResponse response = client.update(updateRequest).get();
        System.out.println(response);

}


output:
UpdateResponse[index=mytest,type=test,id=AV8CfcSLGnilLCUryoEl,version=2,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]

MultiGetクエリー複数index
public static void multiIndex(TransportClient client) throws Exception {
        MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
                .add("mytest","test","AV8CfcSLGnilLCUryoEl") //  index
                .add("instestdb_business_log-2017.09","instestdb_business_log","AV7KHPtGDF9uyeK_lXln") //  index
                .get();

        for(MultiGetItemResponse itemResponses : multiGetItemResponses) {
            GetResponse response = itemResponses.getResponse();
            if(response.isExists()) { 
                String json = response.getSourceAsString(); //   _source field
                System.out.println(json);
            }

        }
    }


Bulk APIは一度に複数の追加と削除を要求する
public static void BulkRequest(TransportClient client) throws Exception {
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        IndexRequestBuilder index1 = client.prepareIndex("mytest", "test");
        IndexRequestBuilder index2 = client.prepareIndex("mytest", "test");

        Map resource = new HashMap<>();
        resource.put("name","  ");
        resource.put("price",5577);
        resource.put("description","  z460");

        index1.setSource(resource);

        Map resource1 = new HashMap<>();
        resource1.put("name","  2");
        resource1.put("price",4577);
        resource1.put("description","    ");

        index1.setSource(resource);
        index2.setSource(resource1);

        bulkRequest.add(index1);
        bulkRequest.add(index2);


        BulkResponse bulkResponse = bulkRequest.get();


        if(bulkResponse.hasFailures()) {
            System.out.println(bulkResponse.buildFailureMessage());
        }

        bulkResponse.forEach(response ->{
            System.out.println(response.getId());
        });

    }

query dsl使用
import static org.elasticsearch.index.query.QueryBuilders.*;

 Settings settings = Settings.builder()
                .put("cluster.name", "hbz-6-test").build();
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        allquery(client); //   query dsl  

        client.close();


Match All Queryはすべてのデータをクエリーします
public static void allquery(TransportClient client) throws Exception{
        QueryBuilder qb = matchAllQuery();
        SearchResponse response = client.prepareSearch("mytest").setTypes("test").setSize(3).setQuery(qb).get();

        System.out.println("length: "+response.getHits().getHits().length );
        if(response.getHits().getTotalHits() != 0) {
            for (SearchHit hit : response.getHits().getHits()) {

                System.out.println(hit.getSourceAsString());
            }
        }
    }


Match Queryは単一条件のデータを問い合わせる
public static void myMatchQuery(TransportClient client) throws Exception {
        QueryBuilder qb = matchQuery("name","mac");

        SearchResponse response = client.prepareSearch("mytest").setTypes("test").setQuery(qb).get();
        System.out.println("length: "+response.getHits().getHits().length );
        if(response.getHits().getTotalHits() != 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit.getScore()+" --> "+hit.getSourceAsString());
            }

        }
    }


MultiMatchQuery複数のフィールドでキーワードを検索
  QueryBuilder qb = multiMatchQuery("mac","description","name"); //mac       description,name     


Common Terms Query検索term
public static void myCommonTermsQuery(TransportClient client ) throws Exception{
        QueryBuilder qb = commonTermsQuery("description","mac");
        print(qb,client);
    }


Simple Query String Query単純文字列クエリーでは、正則を使用できます.
public static void mySimpleQueryString(TransportClient client ) {
        QueryBuilder qb = queryStringQuery("mac*^2").field("name");
        print(qb,client);
    }


term検索キーワード1つ
public static void myTermQuery(TransportClient client) {
        QueryBuilder qb = termQuery("name","mac2");
        print(qb,client);
    }

terms検索キーワード複数
   QueryBuilder qb = termsQuery("name_str","  ","  ");
   print2(qb,client);

range query範囲検索
public static void myRangeQuery(TransportClient client){
        QueryBuilder qb = rangeQuery("price").from(3399)
                .to(6399)
                .includeLower(true)
                .includeUpper(false);

        print2(qb,client);

    }

    QueryBuilder qb = rangeQuery("price").gte(3399).lt(6399);


Exists Queryルックアップフィールドが存在するかどうかはすべてのデータを返し、存在しない場合は0を返します.
public static void myExistsQuery(TransportClient client) {
        QueryBuilder qb = existsQuery("name_str");
        print2(qb,client);
    }


Wildcard Queryワイルドカードクエリー
QueryBuilder qb = wildcardQuery("user", "k?mc*");

Regexp Queryは正規表現のクエリーをサポート

QueryBuilder qb = regexpQuery("name.first", "s.*y");

Fuzzy Queryファジイクエリ

QueryBuilder qb = fuzzyQuery(
    "name",
    "kimzhy"
);

ids Queryはidクエリに基づいて
QueryBuilder qb = idsQuery("my_type", "type2")
    .addIds("1", "4", "100");

QueryBuilder qb = idsQuery() 
    .addIds("AV8HhVC8FiG-4m4G2rYp","AV8HhVB6FiG-4m4G2rYm");


複合クエリー
Contant Score Query指定score
  QueryBuilder qb = constantScoreQuery(matchQuery("name_str", "  ")).boost(3.0f);

Bool Query must mustNot shouldクエリ
すべてのmust文が一致し、すべてのmust_not句は一致しない必要がありますが、いくつのshould句が一致するべきですか?デフォルトでは、should句を一致させる必要はありません.例外として、must句がない場合は、少なくとも1つのshould句を一致させる必要があります.
public static void myBoolQuery(TransportClient client) {
        QueryBuilder qb = boolQuery().must(termQuery("name_str","  "))
                .filter(matchQuery("price",3599))
                .filter(matchQuery("description","lihao"));
        print2(qb, client);
    }

    QueryBuilder qb = boolQuery()
    .must(termQuery("content", "test1"))
    .must(termQuery("content", "test4"))
    .mustNot(termQuery("content", "test2"))
    .should(termQuery("content", "test3"))  
    .filter(termQuery("content", "test5"));

GET mttest-2017.10.41/web1/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "request": "choosehospital/index"
          }
        },
        {
          "match": {
            "response": "500"
          }
        }
      ]
    }
  }
}

indices queryクエリー複数index
複数のindexをクエリーするために使用され、指定された内のindexに対して、指定された内部queryを実行します.指定外のindexの場合、no_を実行します.match_query設定の条件

private static void print(QueryBuilder qb, TransportClient client) {
        SearchResponse response = client.prepareSearch("mytest").setTypes("test").setQuery(qb).get();
        System.out.println("length: " + response.getHits().getHits().length);
        if (response.getHits().getTotalHits() != 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit.getScore() + " --> " + hit.getSourceAsString());
            }

        }
    }

    private static void print2(QueryBuilder qb, TransportClient client) {
        SearchResponse response = client.prepareSearch("mytest_1").setTypes("test").setQuery(qb).get();
        System.out.println("length: " + response.getHits().getHits().length);
        if (response.getHits().getTotalHits() != 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit.getScore() + " --> " + hit.getSourceAsString());
            }

        }
    }


scrollページング

public static void main(String ...arg) throws Exception {

        //     
        Settings  settings = Settings.builder()
                .put("cluster.name","hbz-6-test").build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));


        //      
        QueryBuilder qb = termQuery("name_str","   ");


        //   price         2           sroll  scrollid
        SearchResponse scrollResp = client.prepareSearch("mytest_1").setTypes("test")
                .addSort("price", SortOrder.DESC)
                .setScroll(new TimeValue(30000))
                .setQuery(qb)
                .setSize(2).get();

        System.out.println("length: " + scrollResp.getHits().getHits().length);
        int count = 1;
        do{
            System.out.println("  " +count+ "  ");
            System.out.println();
            for (SearchHit hit : scrollResp.getHits().getHits()){
                System.out.println(hit.getScore() + " --> " +hit.getSourceAsString());
            }


            System.out.println("scrollid:  "+scrollResp.getScrollId());

            //  sroll id
            scrollResp =client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
            System.out.println();

            count++;

        } while (scrollResp.getHits().getHits().length !=0);


        client.close();

    }


prepareMultiSearch複数条件クエリー
public class MultiSearchDemo {

    public static void main(String ...arg) throws Exception{
        Settings settings = Settings.builder().put("cluster.name", "hbz-6-test").build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));


       QueryBuilder query1 = termQuery("name_str","  ");
       QueryBuilder query2 = termQuery("name_str","  ");

        SearchRequestBuilder srb1 = client.prepareSearch("mytest_1").setTypes("test").setQuery(query1);
        SearchRequestBuilder srb2 = client.prepareSearch("mytest_1").setTypes("test").setQuery(query2);

        MultiSearchResponse sr = client.prepareMultiSearch().add(srb1).add(srb2).get();

        long nbHits =0;
        for(MultiSearchResponse.Item item : sr.getResponses()) {
            SearchResponse response = item.getResponse();
            nbHits += response.getHits().getTotalHits();

            if(response.getHits().getHits().length >0) {

                for(SearchHit hit : response.getHits().getHits()) {
                    System.out.println(hit.getScore()+"  ----->  "+hit.getSourceAsString());
                }

            }
            System.out.println("-------------------------");
        }

        System.out.println(nbHits);

        client.close();

    }
}

じゅうごう
概要
ESの集約フレームワークは、複雑な統計解析機能を提供するために、クエリによって得られたデータをグループ化して集計することを提供する.
ESは1回の集約クエリにおいて,集約の具体的な結果を同時に得て再び集約することができ,すなわち集約はネストすることができることをサポートする.
これは、1回の操作で複数回の集約結果を得ることができ、複数回の要求を回避し、ネットワークとサーバの負担を軽減するのに役立ちます.
集約のタイプ
  • Bucketing(バケツ)集約:異なる「バケツ」を区分し、データを異なる「バケツ」に割り当ててから集約します.sqlのgroup文の意味によく似ています.
  • Metric(指標)集約:指標集約は主にnumberタイプのデータに対して、1組のドキュメントの中で、集約する指標の追跡と計算を維持して、ESが比較的に多い計算の仕事をする必要がある.
  • Pipeline(パイプライン)集約:他の集約出力を集約するための結果、および関連指標
  • 集約の基本構文
    "aggregations" : {                      //      ,    "aggs"
        "" : {            //     ,        
            "" : {         //    ,   "histogram" "avg"
                
            }
            [,"meta" : {  [] } ]?
            [,"aggregations" : { []+ } ]?
        }
        [,"" : { ... } ]*  ////           ,  Bucketing      
    }
    

    GET mytest_1/test/_search
    {
      "aggs" : {
            "avg_price" : { "avg" : { "field" : "price" } }
        }
    }
    

    output:
    { "aggregations": {
        "avg_price": {
          "value": 4954.555555555556
        }
      }
    

    Metric使用
    平均値を求める
    public static void main(String ...arg) throws Exception {
    
            Settings settings = Settings.builder().put("cluster.name", "hbz-6-test").build();
    
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
    
    
            avg(client);
    
    
    
            client.close();
    
    
        }
    
         private static void avg(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
    
            SearchResponse sr = search.addAggregation(AggregationBuilders.avg("avg_price").field("price")).execute().actionGet();
    
            Avg result = sr.getAggregations().get("avg_price");
            System.out.println(result.getValue());
        }
    
    

    POST mytest_1/test/_search?size=0
    {
      "aggs" : {
            "avg_price" : {
              "avg" : { "field" : "price" }
            }
        }
    }
    

    POST mytest_1/test/_search?size=0
    {
        "aggs":{
            "all_cats":{
                "terms":{
                    "field":"tag.keyword"
                },
                "aggs":{
                    "avg_price":{
                        "avg":{
                            "field":"price"
                        }
                    }
                }
            }
        }
    }
    

    output:
    "aggregations": {
        "all_cats": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "   ",
              "doc_count": 8,
              "avg_price": {
                "value": 5124
              }
            },
            {
              "key": "  ",
              "doc_count": 4,
              "avg_price": {
                "value": 5649
              }
            },
            {
              "key": "  ",
              "doc_count": 2,
              "avg_price": {
                "value": 4399
              }
            },
            {
              "key": "  ",
              "doc_count": 1,
              "avg_price": {
                "value": 2399
              }
            },
            {
              "key": "  ",
              "doc_count": 1,
              "avg_price": {
                "value": 7199
              }
            }
          ]
        }
      }
    

    分類して平均値を求める
    PUT mytest_1/_mapping/test
    {
      "properties": {
        "tag": { 
          "type":     "text",
          "fielddata": true
        }
      }
    }
    
    private static void avg1(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setSize(0).setTypes("test");
    
            TermsAggregationBuilder tag = AggregationBuilders.terms("tags").field("tag.keyword");
            AvgAggregationBuilder price = AggregationBuilders.avg("avg_price").field("price");
            tag.subAggregation(price);
    
            SearchResponse sr = search.addAggregation(tag).execute().actionGet();
    
            System.out.println(sr);
        }
    
    

    Cardinality重複除外
    単一のデータを要約し、重複しない値の数を計算します.
    public static void main(String... arg) throws Exception {
    
            Settings settings = Settings.builder().put("cluster.name", "hbz-6-test").build();
    
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    
    
            cardinality(client);
    
    
            client.close();
    
    
        }
    
      private static void cardinality(TransportClient client) {
    
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
            SearchResponse sr = search.addAggregation(AggregationBuilders.cardinality("type_count").field("price")).execute().actionGet();
    
            Cardinality result = sr.getAggregations().get("type_count");
    
            System.out.println("type_count: "+result.getValue());
    
        }
    

    POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "type_count" : {
                "cardinality" : {
                    "field" : "price"
                }
            }
        }
    }
    

    output:
    {
      "took": 7,
      "timed_out": false,
      "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
      },
      "hits": {
        "total": 8,
        "max_score": 0,
        "hits": []
      },
      "aggregations": {
        "type_count": {
          "value": 6
        }
      }
    }
    

    Stats集約操作count min max avg sum
    private static void stats(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
            SearchResponse sr =  search.addAggregation(AggregationBuilders.stats("price_stats").field("price")).execute().actionGet();
    
           Stats stats = sr.getAggregations().get("price_stats");
            System.out.println(stats.getAvgAsString());
            System.out.println(stats.getMaxAsString());
            System.out.println(stats.getMinAsString());
            System.out.println(stats.getSumAsString());
    
        }
    
    

    POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "price_stats" : { "extended_stats" : { "field" : "price" } }
        }
    }
    

    output:
    "aggregations": {
        "price_stats": {
          "count": 8,
          "min": 2399,
          "max": 7199,
          "avg": 5124,
          "sum": 40992,
          "sum_of_squares": 231958008,
          "variance": 2739375,
          "std_deviation": 1655.1057368035433,
          "std_deviation_bounds": {
            "upper": 8434.211473607087,
            "lower": 1813.7885263929134
          }
        }
      }
    
    

    Percentilesパーセント対応する値を表示
    これは、集約ドキュメント内のパーセンテージまたは区間で対応する観測値を計算するための多値の指標の集まりです.
  • デフォルトpercentileの区間は[1,5,25,50,75,95,99]です.
  • の観測値は通常近似され、計算には多くの異なるアルゴリズムがある.

  • 例えば、95番目のパーセンテージは、観察された値の95%より大きい値である.
    POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "price_percent" : {
                "percentiles" : {
                    "field" : "price" 
                }
            }
        }
    }
    

    POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "price_percent" : {
                "percentiles" : {
                    "field" : "price" ,
                    "percents" : [0.1,50,95, 99, 100]  //        
                }
            }
        }
    }
    
    

    output:
    "aggregations": {
        "price_percent": {
          "values": {
            "1.0": 2468.9999999999995,
            "5.0": 2749,
            "25.0": 3549,
            "50.0": 5799,
            "75.0": 6399,
            "95.0": 6918.999999999999,
            "99.0": 7143
          }
    
    
    private static void percentile(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
            SearchResponse sr =  search.addAggregation(AggregationBuilders.percentiles("price_percent").field("price")).execute().actionGet();
    
           Percentiles percentile = sr.getAggregations().get("price_percent");
    
           System.out.println(percentile.percentileAsString(80));
        }
    
        //        
        private static void percentile2(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
            SearchResponse sr =  search.addAggregation(AggregationBuilders.percentiles("price_percent").percentiles(0.1,50,95, 99, 100).field("price")).execute().actionGet();
    
            System.out.println(sr);
            Percentiles percentile = sr.getAggregations().get("price_percent");
    
            System.out.println(percentile.percentileAsString(80));
        }
    
    

    Value Countは集約値の数を計算します
    POST mytest_1/test/_search?size=0
    {
    "aggs" : {
            "types_count" : { "value_count" : { "field" : "price" } }
        }
    
    }  
    

    out:
    "aggregations": {
        "types_count": {
          "value": 8
        }
    
    
    private static void valueCount(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
            SearchResponse sr =search.addAggregation(AggregationBuilders.count("value_count").field("price")).execute().actionGet();
           ValueCount valueCount = sr.getAggregations().get("value_count");
           System.out.println(valueCount.getValue());
    
        }
    
    

    TOP hits
    条件を満たす前のn個のデータを取得するために使用される.含まれるオプションはfrom、size、sortです.
    private static void topHits(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test");
    
            TopHitsAggregationBuilder addtion = AggregationBuilders.topHits("top_price_hits").sort("price", SortOrder.DESC).fieldDataField("price")
                    .size(5);
    
            SearchResponse sr =search.addAggregation(addtion).execute().actionGet();
           TopHits topHits = sr.getAggregations().get("top_price_hits");
           System.out.println();
            SearchHit[] hits = topHits.getHits().internalHits();
            for(SearchHit searchHit : hits) {
                System.out.println(searchHit.getSourceAsString());
    
            }
    
        }
    

    bucket使用
    Histogram
    棒グラフが集約され、ドキュメント内の変更フィールドに基づいてグループ化されます.1つのドキュメントはパスに属し、計算プロセスは大体次のようになります.
    rem = value % interval
    if (rem < 0) {
        rem += interval
    }
    bucket_key = value - rem
    

    設定可能なパラメータ:
  • field:フィールド、数値タイプ
  • でなければなりません.
  • interval:バケツ間隔
  • min_doc_count:最小ドキュメント数、バケツフィルタリング、これ以上のドキュメントのバケツのみが
  • を返します.
  • extended_bounds:範囲拡張
  • order:バケツをソートし、histogramが重み付け集約タイプの「直接」サブ集約を集約する場合、ソートはサブ集約の結果
  • を使用することができる.
  • offset:バケツ境界シフト、デフォルトは0から
  • keyed:hash構造は戻り、デフォルトではバケツ
  • が配列で返されます.
  • missing:デフォルトの設定
  • POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "prices" : {
                "histogram" : {
                    "field" : "price",
                    "interval" : 2000
                }
            }
        }
    }
    
    

    out:
    "aggregations": {
        "prices": {
          "buckets": [
            {
              "key": 2000,
              "doc_count": 3
            },
            {
              "key": 4000,
              "doc_count": 1
            },
            {
              "key": 6000,
              "doc_count": 4
            }
          ]
        }
    
    
    private static void histogram(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test").setSize(0);
            HistogramAggregationBuilder addtion = AggregationBuilders.histogram("prices").interval(2000).field("price");
    
            SearchResponse sr = search.addAggregation(addtion).execute().actionGet();
    
           Histogram histogram = sr.getAggregations().get("prices");
           histogram.getBuckets().forEach(bucket->{
               System.out.println(bucket.getKeyAsString()+" ---->  "+bucket.getDocCount());
           });
        }
    
    

    Range
    範囲集約は、あるフィールドの値を設定した範囲でグループ化します.
    POST mytest_1/test/_search?size=0
    {
        "aggs" : {
            "price_ranges" : {
                "range" : {
                    "field" : "price",
                    "ranges" : [
                        { "to" : 3000 },
                        { "from" : 3000, "to" : 5000 },
                        { "from" : 5000 }
                    ]
                }
            }
        }
    }
    
    

    out:
    "aggregations": {
        "price_ranges": {
          "buckets": [
            {
              "key": "*-3000.0",
              "to": 3000,
              "doc_count": 1
            },
            {
              "key": "3000.0-5000.0",
              "from": 3000,
              "to": 5000,
              "doc_count": 2
            },
            {
              "key": "5000.0-*",
              "from": 5000,
              "doc_count": 5
            }
          ]
        }
    
    
    private static void range(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test").setSize(0);
            AggregationBuilder addtion = AggregationBuilders.range("price_ranges").field("price")
                    .addUnboundedTo(3000)
                    .addRange(3000,5000)
                    .addUnboundedFrom(5000);
    
            SearchResponse sr = search.addAggregation(addtion).execute().actionGet();
    
           Range histogram = sr.getAggregations().get("price_ranges");
           histogram.getBuckets().forEach(bucket->{
               String key = bucket.getKeyAsString();
               String from = bucket.getFromAsString();
               String to = bucket.getToAsString();
               long count = bucket.getDocCount();
               System.out.println("key : "+key+"\t form: "+from+"\t to:"+to+"\t count:"+count);
           });
        }
    
    

    Terms
    メタ集約は、指定したフィールド内の各重複しないtermでグループ化され、各グループ内のドキュメントの個数を計算します.
    POST mytest_1/test/_search?size=0
    {
       "aggs" : {
            "all_cats" : {
              "terms" : { "field" : "tag.keyword" }
            }
       }
    }
    

    Filtersろ過
    複数のフィルタ条件を使用して、現在のドキュメントをフィルタする集約です.各フィルタには、それを満たすすべてのドキュメントが含まれます.
    複数のbucketで重複する可能性があります.
    POST mytest_1/test/_search?size=0
    {
      "size": 0,
      "aggs" : {
        "messages" : {
          "filters" : {
            "filters" : {
              "filter1" :   { "match" : { "tag" : "  "   }},
              "filter2" : { "match" : { "tag" : "  " }}
            }
          }
        }
      }
    }
    

    out:
    "aggregations": {
        "messages": {
          "buckets": {
            "filter1": {
              "doc_count": 2
            },
            "filter2": {
              "doc_count": 1
            }
          }
        }
    
    
    private static  void filters(TransportClient client) {
            SearchRequestBuilder search = client.prepareSearch("mytest_1").setTypes("test").setSize(0);
    
            AggregationBuilder aggregation = AggregationBuilders.filters("filters",
                    new FiltersAggregator.KeyedFilter("xiaomi",matchQuery("tag","  ")),
                    new FiltersAggregator.KeyedFilter("daier",matchQuery("tag","  "))
            );
            SearchResponse sr = search.addAggregation(aggregation).execute().actionGet();
            System.out.println(sr);
            Filters agg =sr.getAggregations().get("filters");
            agg.getBuckets().forEach(entry->{
                String key = entry.getKeyAsString();            // bucket key
                long docCount = entry.getDocCount();
                System.out.println("key : "+key+"\t docCount: "+docCount);
            });
    
    
        }
    

    分詞
    分詞のインストール
    https://github.com/medcl/elasticsearch-analysis-ik/tree/v5.5.0
    分詞のテスト
    GET _analyze
    {
      "analyzer": "ik_smart",
      "text": ["       "]
      
    }
    

    bool
  • boolフィルタ:複数のフィルタ条件クエリーの結果をマージするために使用できるブールロジック.オペレータ:
  • を含む
  • must:andに相当する複数のクエリー条件の完全な一致.
  • must_not:複数のクエリー条件の逆一致は、notに相当します.
  • should:orに相当する少なくとも1つのクエリー条件が一致します.

  • リファレンスドキュメント
    https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_structuring_aggregations.html