Catch up on highlights from Firebase at Google I/O 2023. Learn more

एकत्रीकरण प्रश्नों के साथ दस्तावेजों की गणना करें

एक एकत्रीकरण क्वेरी एकल सारांश मान लौटाने के लिए एकाधिक सूचकांक प्रविष्टियों से डेटा संसाधित करती है।

क्लाउड फायरस्टोर 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);
तीव्र
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
let query = db.collection("cities")
let countQuery = query.count
do {
    let snapshot = try await countQuery.getAggregation(source: .server)
    print(snapshot.count)
} catch {
    print(error)
}
उद्देश्य सी
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
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());
      
नोड.जे.एस
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);
तीव्र
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
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)
}
उद्देश्य सी
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
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());
      
नोड.जे.एस
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}")

क्लाउड फायरस्टोर सुरक्षा नियम count() एकत्रीकरण प्रश्नों पर उसी तरह काम करते हैं जैसे दस्तावेज़ लौटाने वाले सामान्य प्रश्नों पर। दूसरे शब्दों में, यदि और केवल यदि आपके नियम ग्राहकों को कुछ संग्रह या संग्रह समूह प्रश्नों को निष्पादित करने की अनुमति देते हैं, तो ग्राहक उन प्रश्नों पर count() एकत्रीकरण भी कर सकते हैं। क्लाउड फायरस्टोर सुरक्षा नियम प्रश्नों के साथ कैसे इंटरैक्ट करते हैं, इसके बारे में और जानें।

सीमाएँ

count() एकत्रीकरण क्वेरी पर निम्नलिखित सीमाओं पर ध्यान दें:

  • count() एकत्रीकरण प्रश्न वर्तमान में केवल प्रत्यक्ष सर्वर प्रतिक्रिया के माध्यम से समर्थित हैं। क्वेरीज़ को केवल क्लाउड फायरस्टोर बैकएंड द्वारा परोसा जाता है, स्थानीय कैश और किसी भी बफ़र किए गए अपडेट को छोड़ दिया जाता है। यह व्यवहार क्लाउड फायरस्टोर लेनदेन के अंदर किए गए कार्यों के समान है। आप वर्तमान में वास्तविक समय के श्रोताओं और ऑफ़लाइन प्रश्नों के साथ count() प्रश्नों का उपयोग नहीं कर सकते हैं।

  • यदि कोई count() एकत्रीकरण 60 सेकंड के भीतर हल नहीं हो पाता है, तो यह DEADLINE_EXCEEDED त्रुटि देता है। प्रदर्शन आपके सूचकांक कॉन्फ़िगरेशन और डेटासेट के आकार पर निर्भर करता है।

    यदि ऑपरेशन 60 सेकंड की समय सीमा के भीतर पूरा नहीं किया जा सकता है, तो बड़े डेटा सेट के लिए काउंटरों का उपयोग करना एक संभावित समाधान है।

  • count() एकत्रीकरण सूचकांक प्रविष्टियों से पढ़ता है और केवल अनुक्रमित फ़ील्ड की गणना करता है।

  • क्वेरी में OrderBy क्लॉज जोड़ने से उन दस्तावेज़ों की गिनती सीमित हो जाती है जहां सॉर्टिंग फ़ील्ड मौजूद है।

मूल्य निर्धारण

count() के लिए मूल्य निर्धारण क्वेरी से मेल खाने वाली सूचकांक प्रविष्टियों की संख्या पर निर्भर करता है। बड़ी संख्या में मिलान वाली प्रविष्टियों के लिए आपसे थोड़ी संख्या में पढ़ने का शुल्क लिया जाता है।

मूल्य निर्धारण की अधिक विस्तृत जानकारी देखें।