اسناد را با جستارهای تجمیع شمارش کنید

یک کوئری تجمیع داده ها را از چندین ورودی فهرست پردازش می کند تا یک مقدار خلاصه واحد را برگرداند.

Cloud Firestore از کوئری جمع آوری count() پشتیبانی می کند. count() به شما امکان می دهد تعداد اسناد را در یک مجموعه یا پرس و جو تعیین کنید. سرور تعداد را محاسبه می کند، و تنها نتیجه، یک عدد صحیح، را به برنامه شما ارسال می کند، در مقایسه با اجرای پرس و جوی کامل، هم در خواندن سند صورتحساب و هم در بایت های منتقل شده صرفه جویی می کند.

جستارهای تجمیع بر پیکربندی فهرست موجودی که عبارت‌های جستجوی شما قبلاً استفاده می‌کردند متکی هستند و متناسب با تعداد ورودی‌های فهرست اسکن‌شده مقیاس می‌شوند. این به این معنی است که مجموعه‌های داده‌های کوچک تا متوسط ​​در 20-40 میلی‌ثانیه انجام می‌شوند، اگرچه تأخیر با تعداد موارد شمارش شده افزایش می‌یابد.

از تجمع count() استفاده کنید

به نمونه داده‌ای که در دریافت داده تنظیم کرده‌ایم مراجعه کنید.

انباشت count() زیر تعداد کل شهرهای مجموعه cities را برمی گرداند.

Web modular API

const coll = collection(db, "cities");
const snapshot = await getCountFromServer(coll);
console.log('count: ', snapshot.data().count);
سریع
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
let query = db.collection("cities")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error)
}
هدف-C
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
FIRCollectionReference *query = [self.db collectionWithPath:@"cities"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                     NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Dart

// Returns number of documents in users collection
db.collection("users").count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
برو
package firestore

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	firestorepb "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func createCountQuery(w io.Writer, projectID string) error {

	// Instantiate the client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}
	defer client.Close()

	collection := client.Collection("users")
	query := collection.Where("born", ">", 1850)

	// `alias` argument--"all"--provides a key for accessing the aggregate query
	// results. The alias value must be unique across all aggregation aliases in
	// an aggregation query and must conform to allowed Document field names.
	//
	// See https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1#document for details.
	aggregationQuery := query.NewAggregationQuery().WithCount("all")
	results, err := aggregationQuery.Get(ctx)
	if err != nil {
		return err
	}

	count, ok := results["all"]
	if !ok {
		return errors.New("firestore: couldn't get alias for COUNT from results")
	}

	countValue := count.(*firestorepb.Value)
	fmt.Fprintf(w, "Number of results from query: %d\n", countValue.GetIntegerValue())
	return nil
}
جاوا
CollectionReference collection = db.collection("cities");
AggregateQuerySnapshot snapshot = collection.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
Node.js
const collectionRef = db.collection('cities');
const snapshot = await collectionRef.count().get();
console.log(snapshot.data().count);
      
پایتون
from google.cloud import firestore
from google.cloud.firestore_v1 import aggregation
from google.cloud.firestore_v1.base_query import FieldFilter


def create_count_query(project_id: str) -> None:
    """Builds an aggregate query that returns the number of results in the query.

    Arguments:
      project_id: your Google Cloud Project ID
    """
    client = firestore.Client(project=project_id)

    collection_ref = client.collection("users")
    query = collection_ref.where(filter=FieldFilter("born", ">", 1800))
    aggregate_query = aggregation.AggregationQuery(query)

    # `alias` to provides a key for accessing the aggregate query results
    aggregate_query.count(alias="all")

    results = aggregate_query.get()
    for result in results:
        print(f"Alias of results from query: {result[0].alias}")
        print(f"Number of results from query: {result[0].value}")

تجمیع count() هر فیلتری را در پرس و جو و هر بند limit را در نظر می گیرد.

Web modular API

const coll = collection(db, "cities");
const q = query(coll, where("state", "==", "CA"));
const snapshot = await getCountFromServer(q);
console.log('count: ', snapshot.data().count);
سریع
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
let query = db.collection("cities").whereField("state", isEqualTo: "CA")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error)
}
هدف-C
توجه: این محصول در اهداف watchOS و App Clip موجود نیست.
FIRQuery *query =
    [[self.db collectionWithPath:@"cities"]
                 queryWhereField:@"state"
                       isEqualTo:@"CA"];
[query.count aggregationWithSource:FIRAggregateSourceServer
                        completion:^(FIRAggregateQuerySnapshot *snapshot,
                                      NSError *error) {
    if (error != nil) {
        NSLog(@"Error fetching count: %@", error);
    } else {
        NSLog(@"Cities count: %@", snapshot.count);
    }
}];

Java

Query query = db.collection("cities").whereEqualTo("state", "CA");
AggregateQuery countQuery = query.count();
countQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) {
        if (task.isSuccessful()) {
            // Count fetched successfully
            AggregateQuerySnapshot snapshot = task.getResult();
            Log.d(TAG, "Count: " + snapshot.getCount());
        } else {
            Log.d(TAG, "Count failed: ", task.getException());
        }
    }
});

Kotlin+KTX

val query = db.collection("cities").whereEqualTo("state", "CA")
val countQuery = query.count()
countQuery.get(AggregateSource.SERVER).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Count fetched successfully
        val snapshot = task.result
        Log.d(TAG, "Count: ${snapshot.count}")
    } else {
        Log.d(TAG, "Count failed: ", task.getException())
    }
}

Dart

// This also works with collectionGroup queries.
db.collection("users").where("age", isGreaterThan: 10).count().get().then(
      (res) => print(res.count),
      onError: (e) => print("Error completing: $e"),
    );
برو
package firestore

import (
	"context"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	firestorepb "cloud.google.com/go/firestore/apiv1/firestorepb"
)

func createCountQuery(w io.Writer, projectID string) error {

	// Instantiate the client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}
	defer client.Close()

	collection := client.Collection("users")
	query := collection.Where("born", ">", 1850)

	// `alias` argument--"all"--provides a key for accessing the aggregate query
	// results. The alias value must be unique across all aggregation aliases in
	// an aggregation query and must conform to allowed Document field names.
	//
	// See https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1#document for details.
	aggregationQuery := query.NewAggregationQuery().WithCount("all")
	results, err := aggregationQuery.Get(ctx)
	if err != nil {
		return err
	}

	count, ok := results["all"]
	if !ok {
		return errors.New("firestore: couldn't get alias for COUNT from results")
	}

	countValue := count.(*firestorepb.Value)
	fmt.Fprintf(w, "Number of results from query: %d\n", countValue.GetIntegerValue())
	return nil
}
جاوا
CollectionReference collection = db.collection("cities");
Query query = collection.whereEqualTo("state", "CA");
AggregateQuerySnapshot snapshot = query.count().get().get();
System.out.println("Count: " + snapshot.getCount());
      
Node.js
const collectionRef = db.collection('cities');
const query = collectionRef.where('state', '==', 'CA');
const snapshot = await query.count().get();
console.log(snapshot.data().count);
      
پایتون
from google.cloud import firestore
from google.cloud.firestore_v1 import aggregation
from google.cloud.firestore_v1.base_query import FieldFilter


def create_count_query(project_id: str) -> None:
    """Builds an aggregate query that returns the number of results in the query.

    Arguments:
      project_id: your Google Cloud Project ID
    """
    client = firestore.Client(project=project_id)

    collection_ref = client.collection("users")
    query = collection_ref.where(filter=FieldFilter("born", ">", 1800))
    aggregate_query = aggregation.AggregationQuery(query)

    # `alias` to provides a key for accessing the aggregate query results
    aggregate_query.count(alias="all")

    results = aggregate_query.get()
    for result in results:
        print(f"Alias of results from query: {result[0].alias}")
        print(f"Number of results from query: {result[0].value}")

قوانین امنیتی Cloud Firestore در پرس‌و‌جوهای جمع‌آوری count() یکسان عمل می‌کنند که در جستارهای عادی که اسناد را برمی‌گردانند. به عبارت دیگر، اگر و تنها در صورتی که قوانین شما به کلاینت‌ها اجازه اجرای پرس‌وجوهای مجموعه یا گروه مجموعه خاص را بدهد، کلاینت‌ها می‌توانند تجمیع count() را روی آن کوئری‌ها نیز انجام دهند. درباره نحوه تعامل قوانین امنیتی Cloud Firestore با جستارها بیشتر بیاموزید.

محدودیت ها

به محدودیت های زیر در پرس و جو تجمع count() توجه کنید:

  • پرس و جوهای جمع آوری count() در حال حاضر فقط از طریق پاسخ مستقیم سرور پشتیبانی می شوند. پرس و جوها فقط توسط پشتیبان Cloud Firestore ارائه می شوند و از حافظه پنهان محلی و هرگونه به روز رسانی بافر صرف نظر می شود. این رفتار مشابه عملیات انجام شده در تراکنش های Cloud Firestore است. در حال حاضر نمی توانید از پرس و جوهای count() با شنوندگان بلادرنگ و پرس و جوهای آفلاین استفاده کنید.

  • اگر تجمع count() نتواند در عرض 60 ثانیه حل شود، یک خطای DEADLINE_EXCEEDED برمی‌گرداند. عملکرد به پیکربندی شاخص شما و اندازه مجموعه داده بستگی دارد.

    اگر عملیات در مهلت 60 ثانیه تکمیل نشود، یک راه حل ممکن استفاده از شمارنده برای مجموعه داده های بزرگ است.

  • تجمع count() از ورودی های فهرست خوانده می شود و فقط فیلدهای نمایه شده را شمارش می کند.

  • افزودن یک بند OrderBy به پرس و جو، تعداد را به اسنادی که فیلد مرتب سازی وجود دارد محدود می کند.

قیمت گذاری

قیمت گذاری برای count() به تعداد ورودی های شاخص مطابق با پرس و جو بستگی دارد. برای تعداد زیادی از ورودی های منطبق، تعداد کمی از خوانده ها از شما دریافت می شود.

اطلاعات دقیق تر قیمت را مشاهده کنید.