Tüm Ürünler
Search
Belge Merkezi

Tablestore:Aggregation

Son Güncelleme:Oct 02, 2026

Bu konuda, veri analizi için Table Store'da toplama özelliğinin nasıl kullanılacağı açıklanmaktadır. Bu özellik sayesinde; minimum, maksimum, toplam, ortalama, sayı, benzersiz sayı ve yüzdelik dilim gibi ölçümleri hesaplayabilir; verileri alan değerine, aralığa, konuma veya filtrelere göre gruplandırabilir; histogramlar ve tarih histogramları oluşturabilir; her gruptan satır alabilir ve iç içe sorgular yapabilirsiniz. Ayrıca karmaşık sorgular oluşturmak için birden fazla toplama işlevini birleştirebilirsiniz.

Yordam

Aşağıdaki şekilde tam toplama yordamı gösterilmektedir.

fig_agg_pro

Bir sorgu tamamlandığında sunucu eşleşen tüm belgeleri toplar. Bu nedenle toplama içeren bir istek, içermeyen bir isteğe göre daha karmaşık işlenir.

Özellikler

Toplama özelliği, çeşitli SQL işlevlerine benzer işlevler sunar. Bunlara MIN(), MAX(), SUM(), AVG(), COUNT(), COUNT(DISTINCT), ANY_VALUE() ve GROUP BY dahildir. Ayrıca yüzdelik dilim istatistikleri, alan değerine göre gruplama, çoklu alan gruplaması, aralığa göre gruplama, coğrafi konuma göre gruplama, filtreye göre gruplama, histogram toplaması, tarih histogramı toplaması ve alt toplama gibi diğer özellikleri de destekler. Aşağıdaki tabloda bu özelliklerin ayrıntıları yer almaktadır.

Özellik

Açıklama

Minimum değer

SQL'deki MIN işlevine benzer şekilde bir alandaki minimum değeri döndürür.

Maksimum değer

SQL max işlevine benzer şekilde bir alanın maksimum değerini döndürür.

Toplam

SQL toplam işlevine benzer şekilde sayısal bir alandaki değerlerin toplamını döndürür.

Ortalama değer

SQL avg işlevine benzer şekilde sayısal bir alanın ortalamasını hesaplar.

Sayı

SQL'deki COUNT işlevine benzer şekilde belirtilen bir alan için değer sayısını veya bir Search Index'teki toplam satır sayısını döndürür.

Benzersiz sayı

SQL'deki COUNT(DISTINCT) işlevine benzer şekilde belirtilen bir alan için benzersiz değer sayısını döndürür.

Yüzdelik dilim istatistikleri

Veri kümesinin yüzdelik dilim dağılımını analiz etmek için yüzdelik dilim istatistiklerini kullanın. Örneğin, rutin işletme ve bakım sırasında P25, P50, P90 ve P99 gibi yüzdelik dilimleri kontrol ederek istek gecikme sürelerinin dağılımını izleyebilirsiniz.

Alan değerine göre grupla

Sorgu sonuçlarını belirtilen bir alanın değerine göre gruplandırır. Aynı alan değerine sahip satırlar bir grup oluşturur. İşlem, her grubun değerini ve satır sayısını döndürür.

Alt toplama

Gruplama toplama işlemleri iç içe geçmeyi destekler; bu sayede bir grup içinde alt toplamalar ekleyebilirsiniz.

Çoklu alan gruplaması

Sorgu sonuçlarını birden fazla alana göre gruplandırır. Bu özellik, sayfalama belirteci kullanılarak sayfalama yapmayı destekler.

Aralığa göre grupla

Sorgu sonuçlarını bir alanın değerine göre özel aralıklara gruplandırır ve her aralık için bir sayı döndürür.

Coğrafi konuma göre grupla

Sorgu sonuçlarını bir başlangıç noktasına olan mesafeye göre gruplandırır. İşlem, belirtilen mesafe aralığı içindeki öğeleri aynı gruba yerleştirir ve her aralık için sayıyı döndürür.

Filtreye göre grupla

Sorgu sonuçlarını belirtilen filtrelere göre gruplandırır. Bu toplama işlemi, her filtreyle eşleşen belge sayısını döndürür. Sonuçlar, filtrelerin eklendiği sırayla döndürülür.

Histogram toplaması

Sorgu sonuçlarını belirtilen bir veri aralığına göre gruplandırır. Alan değerleri aynı aralığa düşen satırlar aynı gruba yerleştirilir. İşlem, her grubun başlangıç değerini ve karşılık gelen satır sayısını döndürür.

Tarih histogramı toplaması

Bir tarih alanı için satırları belirtilen zaman aralığındaki paketlere gruplandırır ve her paket için satır sayısını döndürür.

Toplama grubundan satır al

Sorgu sonuçlarını gruplandırdıktan sonra, en iyi satırlar toplaması her gruptan seçili satırları alır. Bu özellik, MySQL'deki ANY_VALUE(field) işlevine benzer.

Çoklu toplama

Tek bir sorguda birden fazla toplamayı birleştirebilirsiniz.

Not

Birden fazla toplama içeren karmaşık sorgular yanıt süresini etkileyebilir.

İlgili API'ler

Toplama için kullanılan API işlemi Search işlemdir.

Ön Koşullar

Tablestore konsolunu, CLI'yı veya bir SDK'yı kullanarak toplama işlemlerini çalıştırabilirsiniz.

Önemli

Tablestore konsolu ve CLI yalnızca toplama özelliklerinin bir alt kümesini destekler.

Konsol

  1. Index Management sekmesine gidin.

    1. Table Store konsolunda oturum açın.

    2. Üst gezinme çubuğunda bir kaynak grubu ve bölge seçin.

    3. Overview sayfasında örnek adını tıklayın veya Instance Management sütunundaki Actions seçeneğine tıklayın.

    4. Instance Details sekmesinde, Data Table List sekmesinde veri tablosu adını tıklayın veya Actions sütunundaki Index Management seçeneğine tıklayın.

  2. Index Management sekmesinde hedef Search Index'i bulun ve Actions sütunundaki Search seçeneğine tıklayın.

  3. Search iletişim kutusunda sorgu koşullarını belirtin.

    1. Varsayılan olarak tüm sütunlar döndürülür. Belirli sütunları döndürmek için Retrieve All Columns seçeneğini kapatın ve virgülle ayrılmış sütun adlarını girin.

      Not

      Varsayılan olarak Table Store, veri tablosunun birincil anahtar sütunlarını döndürür.

    2. Mantıksal bir operatör seçin: And, Or veya Not.

      And seçerseniz sorgu, belirtilen tüm koşulları karşılayan verileri döndürür. Or seçerseniz sorgu, belirtilen koşullardan en az birini karşılayan verileri döndürür. Not seçerseniz sorgu, belirtilen koşulları karşılamayan verileri döndürür.

    3. Bir dizin alanı seçin, Add seçeneğine tıklayın, ardından alan için sorgu türünü ve değerini ayarlayın.

      Birden fazla dizin alanı için sorgu koşulları eklemek üzere bu adımı tekrarlayabilirsiniz.

    4. Varsayılan olarak sıralama devre dışıdır. Sonuçları belirli bir alana göre sıralamak için Enable Sorting seçeneğini açın, sıralama alanını ekleyin ve sıralama düzenini yapılandırın.

    5. Varsayılan olarak istatistik özelliği devre dışıdır. Belirli alanlar için istatistik toplamak üzere Collect Statistics anahtarını açın, istatistik toplamak istediğiniz alanları ekleyin, ardından gerekirse istatistik türünü, Item ve Default value değerlerini yapılandırın.

      Aynı anda istatistik için birden fazla alan ekleyebilirsiniz. Statistics Type için geçerli değerler Minimum, Maximum, Sum, Average, Count ve Distinct count değerleridir. Default parametresi, bir satırda bir alan yoksa kullanılacak değeri belirtir.

  4. OK seçeneğine tıklayın.

    Indexes sekmesi, sorgunuzla eşleşen verileri ve istatistiksel sonuçları görüntüler.

CLI

Tablestore CLI'da search komutuyla veri sorgularken toplama işlemleri de gerçekleştirebilirsiniz. Desteklenen toplama türleri arasında minimum (min), maksimum (maks), toplam, ortalama (avg) ve sayı bulunur. Daha fazla bilgi için bkz. search index.

  1. search_index arama dizinini kullanarak tablodaki verileri sorgulamak ve analiz etmek için aşağıdaki search komutunu çalıştırın ve tüm dizine alınmış sütunları döndürün.

    search -n search_index --return_all_indexed
  2. İstendiğinde sorgu koşullarını girin.

    Aşağıdaki örnekte, gid sütununun değeri 10'dan küçük veya 77 olan satırları alan bir sorgu gösterilmektedir. Sorgu ayrıca gid sütununun ortalama değerini hesaplar.

    {
        "Offset": -1,
        "Limit": 10,
        "Collapse": null,
        "Sort": null,
        "GetTotalCount": true,
        "Token": null,
        "Query": {
            "Name": "BoolQuery",
            "Query": {
                "MinimumShouldMatch": 1,
                "MustQueries": null,
                "MustNotQueries": null,
                "FilterQueries": null,
                "ShouldQueries": [{
                    "Name": "RangeQuery",
                    "Query": {
                        "FieldName": "gid",
                        "From": null,
                        "To": 10,
                        "IncludeLower": false,
                        "IncludeUpper": false
                    }
                }, {
                    "Name": "TermQuery",
                    "Query": {
                        "FieldName": "gid",
                        "Term": 77
                    }
                }]
            }
        },
        "Aggregations": [{
            "Name": "avg",
            "Aggregation": {
                "AggName": "agg1",
                "Field": "gid",
                "MissingValue": null
            }
        }]
    }

Tablestore SDK'ları

Tablestore SDK for Java, Tablestore SDK for Go, Tablestore SDK for Python, Tablestore SDK for Node.js, Tablestore SDK for .NET ve Tablestore SDK for PHP kullanarak toplama işlemleri gerçekleştirebilirsiniz. Bu konudaki örnek Tablestore SDK for Java kullanmaktadır.

Önemli

Toplama özelliği, bir arama dizini için tanımlanan alan türlerini destekler. Bu türler ve bunların veri tablosu alan türleriyle eşleşmesi hakkında daha fazla bilgi için bkz. Veri türleri.

Minimum değer

SQL'deki MIN işlevine benzer şekilde bir alandaki minimum değeri döndürür.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long, Double ve Date türleri desteklenir.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * The price of each product is listed in the product table. Query the minimum price of the products that are produced in Zhejiang.
     * SQL statement: SELECT min(column_price) FROM product where place_of_production="Zhejiang".
     */
    public void min(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.term("place_of_production", "Zhejiang"))
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.min("min_agg_1", "column_price").missing(100))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsMinAggregationResult("min_agg_1").getValue());
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            TermQuery query = new TermQuery();
            query.setTerm(ColumnValue.fromString("Zhejiang"));
            query.setFieldName("place_of_production");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.term("place_of_production", "Zhejiang").build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            MinAggregation aggregation = new MinAggregation();
            aggregation.setAggName("min_agg_1");
            aggregation.setFieldName("column_price");
            aggregation.setMissing(ColumnValue.fromLong(100));
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // MinAggregation aggregation2 = AggregationBuilders.min("min_agg_1", "column_price").missing(100).build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsMinAggregationResult("min_agg_1").getValue());
        }
    }

Maksimum

SQL max işlevine benzer şekilde bir alanın maksimum değerini döndürür.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long, Double ve Date türleri desteklenir.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * The price of each product is listed in the product table. Query the maximum price of the products that are produced in Zhejiang.
     * SQL statement: SELECT max(column_price) FROM product where place_of_production="Zhejiang".
     */
    public void max(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.term("place_of_production", "Zhejiang"))
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.max("max_agg_1", "column_price").missing(0))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsMaxAggregationResult("max_agg_1").getValue());
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            TermQuery query = new TermQuery();
            query.setTerm(ColumnValue.fromString("Zhejiang"));
            query.setFieldName("place_of_production");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.term("place_of_production", "Zhejiang").build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            MaxAggregation aggregation = new MaxAggregation();
            aggregation.setAggName("max_agg_1");
            aggregation.setFieldName("column_price");
            aggregation.setMissing(ColumnValue.fromLong(100));
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // MaxAggregation aggregation2 = AggregationBuilders.max("max_agg_1", "column_price").missing(100).build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsMaxAggregationResult("max_agg_1").getValue());
        }
    }

Toplam

SQL toplam işlevine benzer şekilde sayısal bir alandaki değerlerin toplamını döndürür.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long ve Double türleri desteklenir.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * The price of each product is listed in the product table. Query the maximum price of the products that are produced in Zhejiang.
     * SQL statement: SELECT sum(column_price) FROM product where place_of_production="Zhejiang".
     */
    public void sum(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.term("place_of_production", "Zhejiang"))
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.sum("sum_agg_1", "column_number").missing(10))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsSumAggregationResult("sum_agg_1").getValue());
        }
    
        // Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            TermQuery query = new TermQuery();
            query.setTerm(ColumnValue.fromString("Zhejiang"));
            query.setFieldName("place_of_production");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.term("place_of_production", "Zhejiang").build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            SumAggregation aggregation = new SumAggregation();
            aggregation.setAggName("sum_agg_1");
            aggregation.setFieldName("column_number");
            aggregation.setMissing(ColumnValue.fromLong(100));
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // SumAggregation aggregation2 = AggregationBuilders.sum("sum_agg_1", "column_number").missing(10).build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsSumAggregationResult("sum_agg_1").getValue());
        }
    }

Ortalama

SQL avg işlevine benzer şekilde sayısal bir alanın ortalamasını hesaplar.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long, Double ve Date türleri desteklenir.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * The sales of each product are listed in the product table. Query the average price of the products that are produced in Zhejiang.
     * SQL statement: SELECT avg(column_price) FROM product where place_of_production="Zhejiang".
     */
    public void avg(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.term("place_of_production", "Zhejiang"))
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.avg("avg_agg_1", "column_price"))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsAvgAggregationResult("avg_agg_1").getValue());
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            TermQuery query = new TermQuery();
            query.setTerm(ColumnValue.fromString("Zhejiang"));
            query.setFieldName("place_of_production");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.term("place_of_production", "Zhejiang").build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            AvgAggregation aggregation = new AvgAggregation();
            aggregation.setAggName("avg_agg_1");
            aggregation.setFieldName("column_price");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // AvgAggregation aggregation2 = AggregationBuilders.avg("avg_agg_1", "column_price").build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsAvgAggregationResult("avg_agg_1").getValue());
        }
    }                    

Sayı

Belirtilen bir alandaki değer sayısını veya bir arama dizinindeki toplam satır sayısını, SQL'deki count işlevine benzer şekilde sayar.

Not

Bir arama dizinindeki toplam satır sayısını veya sorgu koşullarını karşılayan toplam satır sayısını sorgulamak için aşağıdaki yöntemleri kullanın:

  • Toplama özelliğinin sayı özelliğini kullanın. İstekte count parametresini * olarak ayarlayın.

  • Sorgu koşullarını karşılayan satır sayısını almak için sorgu özelliğini kullanın. Sorguda setGetTotalCount parametresini true olarak ayarlayın. Bir arama dizinindeki toplam satır sayısını almak için MatchAllQuery kullanın.

Bir arama dizininde sütunu içeren satır sayısını sorgulamak için count ifadesinin değeri olarak bir sütun adı kullanın. Bu yöntem seyrek sütunları içeren senaryolar için uygundur.

  • Parametreler


    Parameter


    Description


    aggregationName


    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.


    fieldName


    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca aşağıdaki türler desteklenir: Long, Double, Boolean, Keyword, Geo_point ve Date.

  • Örnekler

    /**
     * Penalty records of merchants are recorded in the merchant table. You can query the number of merchants who are located in Zhejiang and for whom penalty records exist. If no penalty record exists for a merchant, the field that corresponds to penalty records also does not exist for the merchant.
     * SQL statement: SELECT count(column_history) FROM product where place_of_production="Zhejiang".
     */
    public void count(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.term("place_of_production", "Zhejiang"))
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.count("count_agg_1", "column_history"))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsCountAggregationResult("count_agg_1").getValue());
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            TermQuery query = new TermQuery();
            query.setTerm(ColumnValue.fromString("Zhejiang"));
            query.setFieldName("place_of_production");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.term("place_of_production", "Zhejiang").build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            CountAggregation aggregation = new CountAggregation();
            aggregation.setAggName("count_agg_1");
            aggregation.setFieldName("column_history");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // CountAggregation aggregation2 = AggregationBuilders.count("count_agg_1", "column_history").build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsCountAggregationResult("count_agg_1").getValue());
        }
    }

Benzeriz sayı

SQL count(distinct) işlevine benzer şekilde belirtilen bir alan için benzersiz değer sayısını döndürür.

Not

Benzersiz değer sayısı yaklaşık bir sayıdır.

  • Benzersiz sayı özelliği kullanılmadan önceki toplam satır sayısı 10.000'den azsa hesaplanan sonuç tam değere yakındır.

  • Benzersiz sayı özelliği kullanılmadan önceki toplam satır sayısı 100 milyon veya daha fazlaysa hata oranı yaklaşık %2'dir.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca aşağıdaki türler desteklenir: Long, Double, Boolean, Keyword, Geo_point ve Date.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * Query the number of distinct provinces from which the products are produced.
     * SQL statement: SELECT count(distinct column_place) FROM product.
     */
    public void distinctCount(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.matchAll())
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.distinctCount("dis_count_agg_1", "column_place"))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsDistinctCountAggregationResult("dis_count_agg_1").getValue());
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            MatchAllQuery query = new MatchAllQuery();
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.matchAll().build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            DistinctCountAggregation aggregation = new DistinctCountAggregation();
            aggregation.setAggName("dis_count_agg_1");
            aggregation.setFieldName("column_place");
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // DistinctCountAggregation aggregation2 = AggregationBuilders.distinctCount("dis_count_agg_1", "column_place").build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            System.out.println(resp.getAggregationResults().getAsDistinctCountAggregationResult("dis_count_agg_1").getValue());
        }
    }

Yüzdelik dilim istatistikleri

Veri kümesinin yüzdelik dilim dağılımını analiz etmek için yüzdelik dilim istatistiklerini kullanın. Örneğin, rutin işletme ve bakım sırasında P25, P50, P90 ve P99 gibi yüzdelik dilimleri kontrol ederek istek gecikme sürelerinin dağılımını izleyebilirsiniz.

Not

Sonuçların doğruluğunu artırmak için p1 ve p99 gibi uç yüzdelik dilim değerlerini belirtmenizi öneririz. p50 gibi diğer değerler yerine uç yüzdelik dilim değerleri kullanıldığında döndürülen sonuçlar daha doğru olur.

  • Parametreler

    Parameter

    Description

    aggregationName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long, Double ve Date türleri desteklenir.

    percentiles

    p50, p90 ve p99 gibi yüzdelik dilimler. Bir veya daha fazla yüzdelik dilim belirtebilirsiniz.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * Analyze the distribution of the response time of each request that is sent to the system by using percentiles.
     */
    public void percentilesAgg(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("indexName")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.matchAll())
                                    .limit(0) //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addAggregation(AggregationBuilders.percentiles("percentilesAgg", "latency")
                                            .percentiles(Arrays.asList(25.0d, 50.0d, 99.0d))
                                            .missing(1.0))
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the results.
            PercentilesAggregationResult percentilesAggregationResult = resp.getAggregationResults().getAsPercentilesAggregationResult("percentilesAgg");
            for (PercentilesAggregationItem item : percentilesAggregationResult.getPercentilesAggregationItems()) {
                System.out.println("key:" + item.getKey() + " value:" + item.getValue().asDouble());
            }
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            MatchAllQuery query = new MatchAllQuery();
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.matchAll().build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            PercentilesAggregation aggregation = new PercentilesAggregation();
            aggregation.setAggName("percentilesAgg");
            aggregation.setFieldName("latency");
            aggregation.setPercentiles(Arrays.asList(25.0d, 50.0d, 99.0d));
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // AggregationBuilders.percentiles("percentilesAgg", "latency").percentiles(Arrays.asList(25.0d, 50.0d, 99.0d)).missing(1.0).build();
            List<Aggregation> aggregationList = new ArrayList<Aggregation>();
            aggregationList.add(aggregation);
            searchQuery.setAggregationList(aggregationList);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the results.
            PercentilesAggregationResult percentilesAggregationResult = resp.getAggregationResults().getAsPercentilesAggregationResult("percentilesAgg");
            for (PercentilesAggregationItem item : percentilesAggregationResult.getPercentilesAggregationItems()) {
                System.out.println("key:" + item.getKey() + " value:" + item.getValue().asDouble());
            }
        }
    }

Alan değerine göre grupla

Sorgu sonuçlarını belirtilen bir alanın değerine göre gruplandırır. Aynı alan değerine sahip satırlar bir grup oluşturur. İşlem, her grubun değerini ve satır sayısını döndürür.

Not
  • Parametreler

    Parameter

    Description

    groupByName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long, Double, Boolean, Keyword ve Date türleri desteklenir.

    groupBySorter

    Gruplar için sıralama kuralları. Varsayılan olarak gruplar, gruplardaki öğe sayısına göre azalan düzende sıralanır. Birden fazla sıralama kuralı yapılandırırsanız gruplar, kuralların yapılandırıldığı sıraya göre sıralanır. Aşağıdaki sıralama kuralları desteklenir:

    • groupKeySortInAsc: Değere göre alfabetik sıraya göre sırala.

    • groupKeySortInDesc: Değere göre ters alfabetik sıraya göre sırala.

    • rowCountSortInAsc: Satır sayısına göre artan düzende sırala.

    • rowCountSortInDesc (varsayılan): Satır sayısına göre azalan düzende sırala.

    • subAggSortInAsc: Alt toplama sonuçlarından elde edilen değerlere göre artan düzende sırala.

    • subAggSortInDesc: Alt toplama sonuçlarından elde edilen değerlere göre azalan düzende sırala.

    size

    Döndürmek istediğiniz grup sayısı. Varsayılan değer: 10. Maksimum değer: 2000.

    subAggregations

    Her gruptaki veriler üzerinde gerçekleştirilebilecek alt toplama işlemleri; maksimum değer, toplam veya ortalama değer gibi.

    subGroupBys

    Verileri daha da gruplandırmak için her üst gruptaki veriler üzerinde gerçekleştirilebilecek alt gruplama işlemleri.

  • Örnekler

    Tek alana göre grupla

    /**
     * Query the number of products, and the maximum and minimum product prices in each category.
     * Example of returned results: Fruits: 5. The maximum price is USD 2, and the minimum price is USD 0.5. Toiletries: 10. The maximum price is USD 13, and the minimum price is USD 0.1. Electronic devices: 3. The maximum price is USD 1,160, and the minimum price is USD 310. Other products: 15. The maximum price is USD 130, and the minimum price is USD 11.
     */
    public void groupByField(SyncClient client) {
        //Use builder to create a query statement.
        {
            SearchRequest searchRequest = SearchRequest.newBuilder()
                    .tableName("<TABLE_NAME>")
                    .indexName("<SEARCH_INDEX_NAME>")
                    .searchQuery(
                            SearchQuery.newBuilder()
                                    .query(QueryBuilders.matchAll())
                                    .limit(0)  //If you want to obtain only the aggregation results instead of specific data, set limit to 0 to improve query performance.
                                    .addGroupBy(GroupByBuilders
                                            .groupByField("name1", "column_type")
                                            .addSubAggregation(AggregationBuilders.min("subName1", "column_price"))
                                            .addSubAggregation(AggregationBuilders.max("subName2", "column_price"))
                                    )
                                    .build())
                    .build();
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            for (GroupByFieldResultItem item : resp.getGroupByResults().getAsGroupByFieldResult("name1").getGroupByFieldResultItems()) {
                //Display values.
                System.out.println(item.getKey());
                //Display the number of rows.
                System.out.println(item.getRowCount());
                //Display the minimum prices.
                System.out.println(item.getSubAggregationResults().getAsMinAggregationResult("subName1").getValue());
                //Display the maximum prices.
                System.out.println(item.getSubAggregationResults().getAsMaxAggregationResult("subName2").getValue());
            }
        }
    
        //Create a query statement without using builder.
        {
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.setTableName("<TABLE_NAME>");
            searchRequest.setIndexName("<SEARCH_INDEX_NAME>");
    
            SearchQuery searchQuery = new SearchQuery();
            MatchAllQuery query = new MatchAllQuery();
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses TermQuery to create a query statement.
            // Query query2 = QueryBuilders.matchAll().build();
    
            searchQuery.setQuery(query);
            searchQuery.setLimit(0);
    
            GroupByField groupByField = new GroupByField();
            groupByField.setGroupByName("name1");
            groupByField.setFieldName("column_type");
            //Configure sub-aggregation operations.
            MinAggregation minAggregation = AggregationBuilders.min("subName1", "column_price").build();
            MaxAggregation maxAggregation = AggregationBuilders.max("subName2", "column_price").build();
            groupByField.setSubAggregations(Arrays.asList(minAggregation, maxAggregation));
    
            //In the following comment, builder is used to create a query statement. The method that uses builder to create a query statement has the same effect as the method that uses aggregation to create a query statement.
            // GroupByBuilders.groupByField("name1", "column_type")
            //        .addSubAggregation(AggregationBuilders.min("subName1", "column_price"))
            //        .addSubAggregation(AggregationBuilders.max("subName2", "column_price").build());
            List<GroupBy> groupByList = new ArrayList<GroupBy>();
            groupByList.add(groupByField);
            searchQuery.setGroupByList(groupByList);
            searchRequest.setSearchQuery(searchQuery);
    
            //Execute the query statement.
            SearchResponse resp = client.search(searchRequest);
            //Obtain the aggregation results.
            for (GroupByFieldResultItem item : resp.getGroupByResults().getAsGroupByFieldResult("name1").getGroupByFieldResultItems()) {
                //Display values.
                System.out.println(item.getKey());
                //Display the number of rows.
                System.out.println(item.getRowCount());
                //Display the minimum prices.
                System.out.println(item.getSubAggregationResults().getAsMinAggregationResult("subName1").getValue());
                //Display the maximum prices.
                System.out.println(item.getSubAggregationResults().getAsMaxAggregationResult("subName2").getValue());
            }
        }
    }

    İç içe modda çoklu alanlara göre grupla

    /**
     * Example of grouping query results by multiple fields in nested mode.
     * In a search index, use two groupBy fields in nested mode to achieve the same effect as using multiple groupBy fields in an SQL statement.
     * SQL statement: select a,d, sum(b),sum(c) from user group by a,d.
     */
    public void GroupByMultiField(SyncClient client) {
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .returnAllColumns(true)   //Set returnAllColumns to false and specify a value for addColumesToGet to obtain better query performance.
            //.addColumnsToGet("col_1","col_2")
            .searchQuery(SearchQuery.newBuilder()
                .query(QueryBuilders.matchAll())   //Specify query conditions. Query conditions can be used in the same manner as the WHERE clause in SQL. Use QueryBuilders.bool() to perform nested queries.
                .addGroupBy(
                    GroupByBuilders
                        .groupByField("unique name_1", "field_a")
                        .size(20)
                        .addSubGroupBy(
                            GroupByBuilders
                                .groupByField("unique name_2", "field_d")
                                .size(20)
                                .addSubAggregation(AggregationBuilders.sum("unique name_3", "field_b"))
                                .addSubAggregation(AggregationBuilders.sum("unique name_4", "field_c"))
                        )
                )
                .build())
            .build();
        SearchResponse response = client.search(searchRequest);
        //Query rows that meet the specified conditions.
        List<Row> rows = response.getRows();
        //Obtain the aggregation results.
        GroupByFieldResult groupByFieldResult1 = response.getGroupByResults().getAsGroupByFieldResult("unique name_1");
        for (GroupByFieldResultItem resultItem : groupByFieldResult1.getGroupByFieldResultItems()) {
            System.out.println("field_a key:" + resultItem.getKey() + " Count:" + resultItem.getRowCount());
            //Obtain the sub-aggregation results.
            GroupByFieldResult subGroupByResult = resultItem.getSubGroupByResults().getAsGroupByFieldResult("unique name_2");
            for (GroupByFieldResultItem item : subGroupByResult.getGroupByFieldResultItems()) {
                System.out.println("field_a " + resultItem.getKey() + " field_d key:" + item.getKey() + " Count: " + item.getRowCount());
                double sumOf_field_b = item.getSubAggregationResults().getAsSumAggregationResult("unique name_3").getValue();
                double sumOf_field_c = item.getSubAggregationResults().getAsSumAggregationResult("unique name_4").getValue();
                System.out.println("sumOf_field_b:" + sumOf_field_b);
                System.out.println("sumOf_field_c:" + sumOf_field_c);
            }
        }
    }

    Toplama için grupları sırala

    /**
     * Example of configuring sorting rules for aggregation.
     * Method: Configure sorting rules by specifying GroupBySorter. If you configure multiple sorting rules, the groups are sorted based on the order in which the rules are configured. GroupBySorter supports sorting in ascending or descending order.
     * By default, the groups are sorted by row count in descending order (GroupBySorter.rowCountSortInDesc()).
     */
    public void groupByFieldWithSort(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .searchQuery(
                SearchQuery.newBuilder()
                    .query(QueryBuilders.matchAll())
                    .limit(0)
                    .addGroupBy(GroupByBuilders
                        .groupByField("name1", "column_type")
                        //.addGroupBySorter(GroupBySorter.subAggSortInAsc("subName1")) //Sort the groups in ascending order based on the values that are obtained from sub-aggregation results.
                        .addGroupBySorter(GroupBySorter.groupKeySortInAsc())           //Sort the groups in ascending order based on the values that are obtained from aggregation results.
                        //.addGroupBySorter(GroupBySorter.rowCountSortInDesc())        //Sort the groups in descending order based on the number of rows that are obtained from the aggregation results in each group.
                        .size(20)
                        .addSubAggregation(AggregationBuilders.min("subName1", "column_price"))
                        .addSubAggregation(AggregationBuilders.max("subName2", "column_price"))
                    )
                    .build())
            .build();
        //Execute the query statement.
        SearchResponse resp = client.search(searchRequest);
    }

İç içe gruplama

Gruplama toplama işlemleri iç içe geçmeyi destekler; bu sayede bir grup içinde alt toplamalar ekleyebilirsiniz.

Not

Performans ve karmaşıklık arasında denge kurmak için maksimum iç içe geçme derinliği sınırlıdır. Daha fazla bilgi için bkz. Search Index sınırları.

  • Yaygın senaryolar

    • Çok düzeyli gruplama (GroupBy + SubGroupBy)

      Birinci düzeyde verileri gruplandırdıktan sonra ikinci düzeyde gruplama gerçekleştirin. Örneğin, önce verileri illere göre gruplandırın, ardından şehirlere göre gruplandırarak her ildeki her şehir için verileri alın.

    • Gruplama ve ardından toplama (GroupBy + SubAggregation)

      Birinci düzeyde verileri gruplandırdıktan sonra her gruptaki veriler üzerinde toplama işlemleri (maksimum değeri veya ortalama değeri hesaplama gibi) gerçekleştirin. Örneğin, verileri illere göre gruplandırdıktan sonra her il grubu için belirli bir ölçümün maksimum değerini alın.

  • Örnekler

    Aşağıdaki örnek, il ve şehre göre iç içe gruplamanın nasıl yapılacağını ve her il için toplam sipariş sayısının yanı sıra her şehir için toplam sipariş sayısını ve maksimum sipariş tutarının nasıl hesaplanacağını göstermektedir.

    public static void subGroupBy(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .tableName("<TABLE_NAME>")
                .indexName("<SEARCH_INDEX_NAME>")
                .returnAllColumns(true)
                .searchQuery(SearchQuery.newBuilder()
                        .query(QueryBuilders.matchAll()).limit(20)
                        //First-level grouping: Group by province and count the number of order IDs (total orders) for each province.
                        //Second-level grouping: Group by city and count the number of order IDs (total orders) for each city, and calculate the maximum order amount for each city.
                        .addGroupBy(GroupByBuilders.groupByField("provinceName", "province")
                                .addSubAggregation(AggregationBuilders.count("provinceOrderCounts", "order_id"))
                                .addGroupBySorter(GroupBySorter.rowCountSortInDesc())
                                .addSubGroupBy(GroupByBuilders.groupByField("cityName", "city")
                                        .addSubAggregation(AggregationBuilders.count("cityOrderCounts", "order_id"))
                                        .addSubAggregation(AggregationBuilders.max("cityMaxAmount", "order_amount"))
                                        .addGroupBySorter(GroupBySorter.subAggSortInDesc("cityMaxAmount"))))
                        .build())
                .build();
        
        //Execute the query statement.
        SearchResponse resp = client.search(searchRequest);
        
        //Obtain the first-level grouping results (total orders for each province)
        GroupByFieldResult results = resp.getGroupByResults().getAsGroupByFieldResult("provinceName");
        for (GroupByFieldResultItem item : results.getGroupByFieldResultItems()) {
            System.out.println("Province:" + item.getKey()
                    + "\tTotal Orders:" + item.getSubAggregationResults().getAsCountAggregationResult("provinceOrderCounts").getValue());
            
            //Obtain the second-level grouping results (total orders and maximum order amount for each city)
            GroupByFieldResult subResults = item.getSubGroupByResults().getAsGroupByFieldResult("cityName");
            for (GroupByFieldResultItem subItem : subResults.getGroupByFieldResultItems()) {
                System.out.println("\t(City)" + subItem.getKey()
                        + "\tTotal Orders:" + subItem.getSubAggregationResults().getAsCountAggregationResult("cityOrderCounts").getValue()
                        + "\tMaximum Order Amount:" + subItem.getSubAggregationResults().getAsMaxAggregationResult("cityMaxAmount").getValue());
            }
        }
    }

Bileşik gruplama

Sorgu sonuçlarını birden fazla alana göre gruplandırır. Bu özellik, sayfalama belirteci kullanarak sayfalama yapmayı destekler.

Önemli

Bu özellik yalnızca Java SDK ve Go SDK'da kullanılabilir.

  • Parametreler

    Parameter

    Description

    groupByName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    sources

    Sorgu sonuçlarını gruplandırmak istediğiniz alanlar. Sorgu sonuçlarını en fazla 32 alana göre gruplandırın ve elde edilen gruplar üzerinde toplama işlemleri gerçekleştirin. Aşağıdaki grup türleri desteklenir:

    • GroupByField: Alan değerine göre grupla. groupByName, fieldName ve groupBySorter parametrelerini yapılandırın.

    • GroupByHistogram: Histograma göre sorgula. groupByName, fieldName, interval ve groupBySorter parametrelerini yapılandırın.

    • GroupByDateHistogram: Tarih histogramına göre sorgula. groupByName, fieldName, interval, timeZone ve groupBySorter parametrelerini yapılandırın.

    Önemli
    • sources içindeki grup öğeleri için yalnızca sözlük sırasına göre grup değeri (groupKeySort) ile sıralama desteklenir. Varsayılan olarak gruplar azalan düzende sıralanır.

    • Belirli bir sütun için bir alan değeri yoksa döndürülen sonuçlardaki değer NULL olur.

    nextToken

    Sonraki veri sayfasını almak için kullanılan sayfalama belirteci. Varsayılan olarak bu parametre boştur.

    İlk istek için nextToken değerini boş bırakın. Tek bir istekte sorgu koşullarını karşılayan tüm veriler döndürülmezse yanıtta nextToken parametresi boş olmaz. Sayfalama sorguları için bu nextToken değerini kullanın.

    Not

    nextToken değerini kalıcı hale getirmeniz veya bir ön uç sayfasına iletmeniz gerekiyorsa kaydetmeden veya iletmeden önce nextToken değerini bir dize olarak kodlamak için Base64 kodlamasını kullanmanızı öneririz. nextToken kendisi bir dize değildir. Kodlama için doğrudan new String(nextToken) kullanırsanız belirteç bilgileri kaybolur.

    size

    Sayfa başına grup sayısı. Varsayılan değer: 10. Maksimum değer: 2000.

    Önemli
    • Döndürülecek grup sayısını sınırlamak istiyorsanız çoğu durumda size parametresini yapılandırmanızı öneririz.

    • size ve suggestedSize parametrelerini aynı anda yapılandıramazsınız.

    suggestedSize

    Döndürülecek grup sayısı. Sunucu tarafında izin verilen maksimum grup sayısından büyük bir değer veya -1 belirtin. Sunucu tarafı, kapasitesine bağlı olarak grup sayısını döndürür.

    Bu parametreyi sunucu tarafında izin verilen maksimum grup sayısından büyük bir değere ayarlarsanız sistem değeri sunucu tarafında izin verilen maksimum grup sayısına ayarlar. Döndürülen gerçek grup sayısı min(suggestedSize, sunucu tarafında izin verilen maksimum grup sayısı, toplam grup sayısı) değerine eşittir.

    Önemli

    Bu parametre, Tablestore'u Apache Spark veya PrestoSQL gibi yüksek verimli bir hesaplama motoruyla birlikte kullandığınız senaryolar için uygundur.

    subAggregations

    Her gruptaki veriler üzerinde gerçekleştirilebilecek alt toplama işlemleri; maksimum değer, toplam veya ortalama değer gibi.

    subGroupBys

    Verileri daha da gruplandırmak için her üst gruptaki veriler üzerinde gerçekleştirilebilecek alt gruplama işlemleri.

    Önemli

    GroupByComposite parametresi subGroupBy içinde desteklenmez.

  • Örnekler

    /**
     * Group and aggregate query results: Group the query results and perform the aggregation operation on the resulting groups based on the parameters such as groupbyField, groupByHistogram, and groupByDataHistogram that are passed to the SourceGroupBy parameter.
     * Return the aggregated results of multiple fields in a flat structure.
     */
    public static void groupByComposite(SyncClient client) {
        GroupByComposite.Builder compositeBuilder = GroupByBuilders
                .groupByComposite("groupByComposite")
                .size(2000)
                .addSources(GroupByBuilders.groupByField("groupByField", "Col_Keyword")
                        .addGroupBySorter(GroupBySorter.groupKeySortInAsc()).build())
                .addSources(GroupByBuilders.groupByHistogram("groupByHistogram", "Col_Long")
                        .addGroupBySorter(GroupBySorter.groupKeySortInAsc())
                        .interval(5)
                        .build())
                .addSources(GroupByBuilders.groupByDateHistogram("groupByDateHistogram", "Col_Date")
                        .addGroupBySorter(GroupBySorter.groupKeySortInAsc())
                        .interval(5, DateTimeUnit.DAY)
                        .timeZone("+05:30").build());
    
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .indexName("<SEARCH_INDEX_NAME>")
                .tableName("<TABLE_NAME>")
                .returnAllColumnsFromIndex(true)
                .searchQuery(SearchQuery.newBuilder()
                        .addGroupBy(compositeBuilder.build())
                        .build())
                .build();
    
        SearchResponse resp = client.search(searchRequest);
    
        while (true) {
            if (resp.getGroupByResults() == null || resp.getGroupByResults().getResultAsMap().size() == 0) {
                System.out.println("groupByComposite Result is null or empty");
                return;
            }
    
            GroupByCompositeResult result = resp.getGroupByResults().getAsGroupByCompositeResult("groupByComposite");
    
            if(!result.getSourceNames().isEmpty()) {
                for (String sourceGroupByNames: result.getSourceNames()) {
                    System.out.printf("%s\t", sourceGroupByNames);
                }
                System.out.print("rowCount\t\n");
            }
    
            for (GroupByCompositeResultItem item : result.getGroupByCompositeResultItems()) {
                for (String value : item.getKeys()) {
                    String val = value == null ? "NULL" : value;
                    System.out.printf("%s\t", val);
    
                }
                System.out.printf("%d\t\n", item.getRowCount());
            }
    
            // Use the token to page through groups.
            if (result.getNextToken() != null) {
                searchRequest.setSearchQuery(
                        SearchQuery.newBuilder()
                                .addGroupBy(compositeBuilder.nextToken(result.getNextToken()).build())
                                .build()
                );
                resp = client.search(searchRequest);
            } else {
                break;
            }
        }
    }

Aralığa göre grupla

Sorgu sonuçlarını bir alanın değerine göre özel aralıklara gruplandırır ve her aralık için bir sayı döndürür.

  • Parametreler


    Parameter


    Description


    groupByName


    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.


    fieldName


    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long ve Double türleri desteklenir.


    range[double_from, double_to)

    Gruplama için değer aralıkları.

    Minimum değeri belirtmek için double_from değerini Double.MIN_VALUE olarak, maksimum değeri belirtmek için double_to değerini Double.MAX_VALUE olarak ayarlayın.


    subAggregation ve subGroupBy

    Alt toplama işlemi. Gruplama sonuçlarına dayalı olarak alt toplama işlemini gerçekleştirin.

    Örneğin, sorgu sonuçlarını satış hacmine ve ile göre gruplandırdıktan sonra belirtilen bir aralıkta satış hacminin en büyük oranına sahip ili alın. Bu sorguyu gerçekleştirmek için GroupByRange içinde GroupByField belirtmeniz gerekir.

  • Örnekler

    /**
     * Group sales volumes based on ranges [0, 1000), [1000, 5000), and [5000, Double.MAX_VALUE) to obtain the sales volume in each range.
     */
    public void groupByRange(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .searchQuery(
                SearchQuery.newBuilder()
                    .query(QueryBuilders.matchAll())
                    .limit(0)
                    .addGroupBy(GroupByBuilders
                        .groupByRange("name1", "column_number")
                        .addRange(0, 1000)
                        .addRange(1000, 5000)
                        .addRange(5000, Double.MAX_VALUE)
                    )
                    .build())
            .build();
        //Execute the query statement.
        SearchResponse resp = client.search(searchRequest);
        //Obtain the aggregation results.
        for (GroupByRangeResultItem item : resp.getGroupByResults().getAsGroupByRangeResult("name1").getGroupByRangeResultItems()) {
    
            //Display the number of rows.
            System.out.println(item.getRowCount());
        }
    }

Coğrafi gruplama

Sorgu sonuçlarını bir başlangıç noktasına olan mesafeye göre gruplandırır. İşlem, belirtilen mesafe aralığı içindeki öğeleri aynı gruba yerleştirir ve her aralık için sayıyı döndürür.

  • Parametreler


    Parameter


    Description


    groupByName


    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.


    fieldName


    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Geo_point türü desteklenir.


    origin(double lat, double lon)

    Merkez noktanın boylam ve enlemi.

    double lat merkez noktanın enlemini belirtir. double lon merkez noktanın boylamını belirtir.


    range[double_from, double_to)

    Gruplama için kullanılan mesafe aralıkları. Birim: metre.

    Minimum değeri belirtmek için double_from değerini Double.MIN_VALUE olarak, maksimum değeri belirtmek için double_to değerini Double.MAX_VALUE olarak ayarlayın.


    subAggregation ve subGroupBy


    Alt toplama işlemi. Gruplama sonuçlarına dayalı olarak alt toplama işlemini gerçekleştirin.

  • Örnekler

    /**
     * Group users based on geographical locations to a Wanda Plaza to obtain the number of users in each distance range. The distance ranges are [0, 1000), [1000, 5000), and [5000, Double.MAX_VALUE). Unit: meters.
     */
    public void groupByGeoDistance(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .searchQuery(
                SearchQuery.newBuilder()
                    .query(QueryBuilders.matchAll())
                    .limit(0)
                    .addGroupBy(GroupByBuilders
                        .groupByGeoDistance("name1", "column_geo_point")
                        .origin(3.1, 6.5)
                        .addRange(0, 1000)
                        .addRange(1000, 5000)
                        .addRange(5000, Double.MAX_VALUE)
                    )
                    .build())
            .build();
        //Execute the query statement.
        SearchResponse resp = client.search(searchRequest);
        //Obtain the aggregation results.
        for (GroupByGeoDistanceResultItem item : resp.getGroupByResults().getAsGroupByGeoDistanceResult("name1").getGroupByGeoDistanceResultItems()) {
           //Display the number of rows.
            System.out.println(item.getRowCount());
        }
    }

Filtreye göre grupla

Sorgu sonuçlarını belirtilen filtrelere göre gruplandırır. Bu toplama işlemi, her filtreyle eşleşen belge sayısını döndürür. Sonuçlar, filtrelerin eklendiği sırayla döndürülür.

  • Parametreler


    Parameter


    Description


    groupByName


    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.


    filter


    Sorgu için kullanılabilecek filtreler. Sonuçlar, filtrelerin belirtildiği sırayla döndürülür.


    subAggregation ve subGroupBy


    Alt toplama işlemi. Gruplama sonuçlarına dayalı olarak alt toplama işlemini gerçekleştirin.

  • Örnekler

    /**
     * Specify the following filters to obtain the number of items that match each filter: The sales volume exceeds 100, the place of origin is Zhejiang, and the description contains Hangzhou.
     */
    public void groupByFilter(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .searchQuery(
                SearchQuery.newBuilder()
                    .query(QueryBuilders.matchAll())
                    .limit(0) 
                    .addGroupBy(GroupByBuilders
                        .groupByFilter("name1")
                        .addFilter(QueryBuilders.range("number").greaterThanOrEqual(100))
                        .addFilter(QueryBuilders.term("place","Zhejiang"))
                        .addFilter(QueryBuilders.match("text","Hangzhou"))
                    )
                    .build())
            .build();
        //Execute the query statement.
        SearchResponse resp = client.search(searchRequest);
        //Obtain the aggregation results based on the order of filters.
        for (GroupByFilterResultItem item : resp.getGroupByResults().getAsGroupByFilterResult("name1").getGroupByFilterResultItems()) {
            //Display the number of rows.
            System.out.println(item.getRowCount());
        }
    }

Histograma göre grupla

Sorgu sonuçlarını belirtilen bir veri aralığına göre gruplandırır. Alan değerleri aynı aralığa düşen satırlar aynı gruba yerleştirilir. İşlem, her grubun başlangıç değerini ve karşılık gelen satır sayısını döndürür.

  • Parametreler

    Parameter

    Description

    groupByName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Long ve Double türleri desteklenir.

    interval

    Toplama sonuçlarını almak için kullanılan veri aralığı.

    fieldRange[min,max]

    Grup sayısını sınırlamak için interval parametresiyle birlikte kullanılan aralık. (fieldRange.max-fieldRange.min)/interval formülü kullanılarak belirlenen grup sayısı 2.000'i aşamaz.

    minDocCount

    Minimum satır sayısı. Bir gruptaki satır sayısı minimum satır sayısından azsa o grup için toplama sonuçları döndürülmez.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

  • Örnekler

    /**
     * Collect statistics on the distribution of users by age group.
     */
    public static void groupByHistogram(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
            .tableName("<TABLE_NAME>")
            .indexName("<SEARCH_INDEX_NAME>")
            .searchQuery(
                SearchQuery.newBuilder()
                    .addGroupBy(GroupByBuilders
                        .groupByHistogram("groupByHistogram", "age")
                        .interval(10)
                        .minDocCount(0L)
                        .addFieldRange(0, 99))
                    .build())
            .build();
        //Execute the query statement.
        SearchResponse resp = ots.search(searchRequest);
        //Obtain the results that are returned when the aggregation operation is performed.
        GroupByHistogramResult results = resp.getGroupByResults().getAsGroupByHistogramResult("groupByHistogram");
        for (GroupByHistogramItem item : results.getGroupByHistogramItems()) {
            System.out.println("key:" + item.getKey().asLong() + " value:" + item.getValue());
        }
    }

Tarih histogramı

Bir tarih alanı için sorgu sonuçlarını belirtilen zaman aralığında paketlere gruplandırır. Her paket aynı aralıktaki satırları içerir ve başlangıç zamanını ve satır sayısını döndürür.

Önemli

Bu özellik için Tablestore Java SDK 5.16.1 veya sonraki bir sürüm gereklidir. Tam sürüm geçmişi için bkz. Java SDK sürüm geçmişi.

  • Parametreler

    Parameter

    Description

    groupByName

    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.

    fieldName

    Toplama işlemini gerçekleştirmek için kullanılan alanın adı. Yalnızca Date türü desteklenir.

    Önemli

    Arama dizinlerinin Date türü, Tablestore SDK for Java V5.13.9 ve sonraki sürümler tarafından desteklenir.

    interval

    İstatistik aralığı.

    fieldRange[min,max]

    Grup sayısını sınırlamak için interval parametresiyle birlikte kullanılan aralık. (fieldRange.max-fieldRange.min)/interval formülü kullanılarak belirlenen grup sayısı 2.000'i aşamaz.

    minDocCount

    Minimum satır sayısı. Bir gruptaki satır sayısı minimum satır sayısından azsa o grup için toplama sonuçları döndürülmez.

    missing

    Toplama işleminin gerçekleştirildiği alan için varsayılan değer; alan değerinin boş olduğu satırlara uygulanır.

    • missing parametresi için bir değer belirtmezseniz satır yoksayılır.

    • missing parametresi için bir değer belirtirseniz bu parametrenin değeri satırın alan değeri olarak kullanılır.

    timeZone

    +hh:mm veya -hh:mm biçimindeki saat dilimi; örneğin +08:00 veya -09:00. Bu parametre yalnızca alan Date türünde olduğunda gereklidir.

    Date türündeki alan için bu parametre belirtilmezse toplama sonuçlarında N saatlik bir sapma oluşabilir. Bu sorunu önlemek için timeZone parametresini belirtin.

  • Örnekler

    /**
     * Collect statistics on the daily distribution of data in the col_date field from 10:00:00 on May 1, 2017 to 13:00:00 May 21, 2017.
     */
    public static void groupByDateHistogram(SyncClient client) {
        //Create a query statement.
        SearchRequest searchRequest = SearchRequest.newBuilder()
        .returnAllColumns(false)
        .indexName("<SEARCH_INDEX_NAME>")
        .tableName("<TABLE_NAME>")
        .searchQuery(
            SearchQuery.newBuilder()
            .query(QueryBuilders.matchAll())
            .limit(0)
            .getTotalCount(false)
            .addGroupBy(GroupByBuilders
                        .groupByDateHistogram("groupByDateHistogram", "col_date")
                        .interval(1, DateTimeUnit.DAY)
                        .minDocCount(1)
                        .missing("2017-05-01 13:01:00")
                        .fieldRange("2017-05-01 10:00", "2017-05-21 13:00:00"))
            .build())
        .build();
        //Execute the query statement.
        SearchResponse resp = ots.search(searchRequest);
        //Obtain the results that are returned when the aggregation operation is performed.
        List<GroupByDateHistogramItem> items = resp.getGroupByResults().getAsGroupByDateHistogramResult("groupByDateHistogram").getGroupByDateHistogramItems();
        for (GroupByDateHistogramItem item : items) {
            System.out.printf("millisecondTimestamp:%d, count:%d \n", item.getTimestamp(), item.getRowCount());
        }
    }

En iyi satırlar toplaması

Sorgu sonuçlarını gruplandırdıktan sonra, en iyi satırlar toplaması her gruptan seçili satırları alır. Bu özellik, MySQL'deki ANY_VALUE(field) işlevine benzer.

Not

En iyi satırlar toplaması kullanırken Search Index nested türde, Geopoint veya dizi türünde alanlar içeriyorsa toplama işlemi her satırın yalnızca birincil anahtarını döndürür. Diğer alanları almak için veri tablosunu ayrı olarak sorgulayın.

  • Parametreler


    Parameter


    Description


    aggregationName


    Toplama işleminin benzersiz adı. Bu ada göre belirli bir toplama işleminin sonuçlarını sorgulayın.


    limit


    Her grup için döndürülebilecek maksimum satır sayısı. Varsayılan olarak yalnızca bir satır veri döndürülür.


    sort


    Gruplardaki verileri sıralamak için kullanılan sıralama yöntemi.


    columnsToGet

    Döndürmek istediğiniz alanlar. Yalnızca arama dizinlerindeki alanlar desteklenir. Dizi, Date, Geopoint ve Nested alanlar desteklenmez.

    Bu parametrenin değeri, SearchRequest içindeki columnsToGet parametresinin değeriyle aynıdır. SearchRequest içinde columnsToGet parametresi için bir değer belirtmeniz yeterlidir.

  • Örnekler

    /**
     * An activity application form of a school contains fields in which information such as the names of students, classes, head teachers, and class presidents can be specified. Group students by class to view the application statistics and the property information of each class.
     * SQL statement: select className, teacher, monitor, COUNT(*) as number from table GROUP BY className.
     */
    public void testTopRows(SyncClient client) {
        SearchRequest searchRequest = SearchRequest.newBuilder()
                .indexName("<SEARCH_INDEX_NAME>")
                .tableName("<TABLE_NAME>")
                .searchQuery(
                        SearchQuery.newBuilder()
                                .query(QueryBuilders.matchAll())
                                .limit(0) 
                                .addGroupBy(GroupByBuilders.groupByField("groupName", "className")
                                        .size(5)  //Specify the number of groups that you want to return. For information about the maximum value that you can specify for the number of groups to return, see the description of the number of groups returned by GroupByField in the "Search index limits" topic.
                                        .addSubAggregation(AggregationBuilders.topRows("topRowsName")
                                                .limit(1)
                                                .sort(new Sort(Arrays.asList(new FieldSort("teacher", SortOrder.DESC)))) //Sort rows by teacher in descending order.
                                        )
                                )
                                .build())
                .addColumnsToGet(Arrays.asList("teacher", "monitor"))
                .build();
        SearchResponse resp = client.search(searchRequest);
        List<GroupByFieldResultItem> items = resp.getGroupByResults().getAsGroupByFieldResult("groupName").getGroupByFieldResultItems();
        for (GroupByFieldResultItem item : items) {
            String className = item.getKey();
            long number = item.getRowCount();
            List<Row> topRows = item.getSubAggregationResults().getAsTopRowsAggregationResult("topRowsName").getRows();
            Row row = topRows.get(0);
            String teacher = row.getLatestColumn("teacher").getValue().asString();
            String monitor = row.getLatestColumn("monitor").getValue().asString();
        }
    }

Çoklu toplama

Tek bir sorguda birden fazla toplamayı birleştirebilirsiniz.

Not

Birden fazla toplama içeren karmaşık sorgular yanıt süresini artırabilir.

Birden fazla toplamayı birleştir

public void multipleAggregation(SyncClient client) {
    //Create a query statement.
    SearchRequest searchRequest = SearchRequest.newBuilder()
        .tableName("<TABLE_NAME>")
        .indexName("<SEARCH_INDEX_NAME>")
        .searchQuery(
            SearchQuery.newBuilder()
                .query(QueryBuilders.matchAll())
                .limit(0) 
                .addAggregation(AggregationBuilders.min("name1", "long"))
                .addAggregation(AggregationBuilders.sum("name2", "long"))
                .addAggregation(AggregationBuilders.distinctCount("name3", "long"))
                .build())
        .build();
    //Execute the query statement.
    SearchResponse resp = client.search(searchRequest);
    //Obtain the minimum value from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsMinAggregationResult("name1").getValue());
    //Obtain the sum from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsSumAggregationResult("name2").getValue());
    //Obtain the number of distinct values from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsDistinctCountAggregationResult("name3").getValue());
}

Toplama ve GroupBy'ı birleştir

public void multipleGroupBy(SyncClient client) {
    //Create a query statement.
    SearchRequest searchRequest = SearchRequest.newBuilder()
        .tableName("<TABLE_NAME>")
        .indexName("<SEARCH_INDEX_NAME>")
        .searchQuery(
            SearchQuery.newBuilder()
                .query(QueryBuilders.matchAll())
                .limit(0)
                .addAggregation(AggregationBuilders.min("name1", "long"))
                .addAggregation(AggregationBuilders.sum("name2", "long"))
                .addAggregation(AggregationBuilders.distinctCount("name3", "long"))
                .addGroupBy(GroupByBuilders.groupByField("name4", "type"))
                .addGroupBy(GroupByBuilders.groupByRange("name5", "long").addRange(1, 15))
                .build())
        .build();
    //Execute the query statement.
    SearchResponse resp = client.search(searchRequest);
    //Obtain the minimum value from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsMinAggregationResult("name1").getValue());
    //Obtain the sum from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsSumAggregationResult("name2").getValue());
    //Obtain the number of distinct values from the results of the aggregation operation.
    System.out.println(resp.getAggregationResults().getAsDistinctCountAggregationResult("name3").getValue());
    //Obtain the values of GroupByField from the results of the aggregation operation.
    for (GroupByFieldResultItem item : resp.getGroupByResults().getAsGroupByFieldResult("name4").getGroupByFieldResultItems()) {
        //Display the keys.
        System.out.println(item.getKey());
        //Display the number of rows.
        System.out.println(item.getRowCount());
    }
    //Obtain the values of GroupByRange from the results of the aggregation operation.
    for (GroupByRangeResultItem item : resp.getGroupByResults().getAsGroupByRangeResult("name5").getGroupByRangeResultItems()) {
        //Display the number of rows.
        System.out.println(item.getRowCount());
    }
}

Ek: Çoklu alan gruplama yöntemlerinin karşılaştırılması

Sorgu sonuçlarını birden fazla alana göre gruplandırmak istiyorsanız iç içe modda groupBy parametresini veya GroupByComposite parametresini kullanın. Aşağıdaki tabloda iç içe modda groupBy parametresi ile GroupByComposite parametresi arasındaki fark açıklanmaktadır.

Feature

groupBy (nested)

Multi-field grouping

size

2000

2000

Limits on fields

En fazla 3 düzey desteklenir.

En fazla 32 düzey desteklenir.

Pagination

Desteklenmez

nextToken parametresi kullanılarak desteklenir

Sorting rules for rows in groups

  • Alfabetik sıraya veya ters alfabetik sıraya göre

  • Artan satır sayısına veya azalan satır sayısına göre

  • Alt toplama sonuçlarından elde edilen değerlere göre artan düzende veya alt toplama sonuçlarından elde edilen değerlere göre azalan düzende

Alfabetik sıraya veya ters alfabetik sıraya göre

Supports aggregation

Evet

Evet

Compatibility

Date türündeki alanlar için sorgu sonuçları belirtilen biçimde döndürülür.

DATE türündeki alanlar için sorgu sonuçları zaman damgası dizeleri olarak döndürülür.