एग्रीगेशन क्वेरी, एक ही जवाब की वैल्यू देने के लिए कई इंडेक्स एंट्री से डेटा प्रोसेस करती है.
Cloud Firestore, एग्रीगेशन की इन क्वेरी के साथ काम करता है:
count()
sum()
average()
Cloud Firestore एग्रीगेशन का हिसाब लगाता है और सिर्फ़ नतीजे को आपके ऐप्लिकेशन में वापस भेजता है. एक पूरी क्वेरी को लागू करने और आपके ऐप्लिकेशन में एग्रीगेशन का हिसाब लगाने की तुलना में, एग्रीगेशन क्वेरी, बिल किए गए दस्तावेज़ और बाइट, दोनों ट्रांसफ़र किए जाने पर सेव की जाती हैं.
एग्रीगेशन की क्वेरी उस मौजूदा इंडेक्स कॉन्फ़िगरेशन पर निर्भर करती हैं जिसका इस्तेमाल आपकी क्वेरी पहले से कर रही हैं. ये क्वेरी और स्कैन की गई इंडेक्स एंट्री के अनुपात में स्केल करती हैं. एग्रीगेशन में आइटम की संख्या बढ़ने पर इंतज़ार का समय बढ़ जाता है.
count()
एग्रीगेशन का इस्तेमाल करना
count()
एग्रीगेशन क्वेरी की मदद से,
किसी कलेक्शन या क्वेरी में दस्तावेज़ों की संख्या तय की जा सकती है.
उदाहरण के तौर पर दिया गया वह डेटा देखें जिसे हमने डेटा पाना सेक्शन में सेट अप किया है.
यहां दिया गया count()
एग्रीगेशन, cities
कलेक्शन में मौजूद शहरों की कुल संख्या दिखाता है.
Web
const coll = collection(db, "cities"); const snapshot = await getCountFromServer(coll); console.log('count: ', snapshot.data().count);
Swift
let query = db.collection("cities") let countQuery = query.count do { let snapshot = try await countQuery.getAggregation(source: .server) print(snapshot.count) } catch { print(error) }
Objective-C
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"), );
शुरू करें
Java
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);
Python
count()
एग्रीगेशन, क्वेरी और किसी भी limit
क्लॉज़ पर फ़िल्टर को ध्यान में रखता है.
Web
const coll = collection(db, "cities"); const q = query(coll, where("state", "==", "CA")); const snapshot = await getCountFromServer(q); console.log('count: ', snapshot.data().count);
Swift
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) }
Objective-C
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"), );
शुरू करें
Java
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);
Python
sum()
एग्रीगेशन का इस्तेमाल करना
किसी क्वेरी से मेल खाने वाली संख्या वाली वैल्यू का कुल योग दिखाने के लिए, sum()
एग्रीगेशन का इस्तेमाल करें—उदाहरण के लिए:
Web
const coll = collection(firestore, 'cities'); const snapshot = await getAggregateFromServer(coll, { totalPopulation: sum('population') }); console.log('totalPopulation: ', snapshot.data().totalPopulation);
Swift
let query = db.collection("cities") let aggregateQuery = query.aggregate([AggregateField.sum("population")]) do { let snapshot = try await aggregateQuery.getAggregation(source: .server) print(snapshot.get(AggregateField.sum("population"))) } catch { print(error) }
Objective-C
FIRQuery *query = [self.db collectionWithPath:@"cities"]; FIRAggregateQuery *aggregateQuery = [query aggregate:@[ [FIRAggregateField aggregateFieldForSumOfField:@"population"]]]; [aggregateQuery aggregationWithSource:FIRAggregateSourceServer completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error fetching aggregate: %@", error); } else { NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); } }];
Java
Query query = db.collection("cities"); AggregateQuery aggregateQuery = query.aggregate(AggregateField.sum("population")); aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() { @Override public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) { if (task.isSuccessful()) { // Aggregate fetched successfully AggregateQuerySnapshot snapshot = task.getResult(); Log.d(TAG, "Sum: " + snapshot.get(AggregateField.sum("population"))); } else { Log.d(TAG, "Aggregation failed: ", task.getException()); } } });
Kotlin+KTX
val query = db.collection("cities") val aggregateQuery = query.aggregate(AggregateField.sum("population")) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { // Aggregate fetched successfully val snapshot = task.result Log.d(TAG, "Sum: ${snapshot.get(AggregateField.sum("population"))}") } else { Log.d(TAG, "Aggregate failed: ", task.getException()) } }
Java
collection = db.collection("cities"); snapshot = collection.aggregate(sum("population")).get().get(); System.out.println("Sum: " + snapshot.get(sum("population")));
Node.js के लिए
const coll = firestore.collection('cities'); const sumAggregateQuery = coll.aggregate({ totalPopulation: AggregateField.sum('population'), }); const snapshot = await sumAggregateQuery.get(); console.log('totalPopulation: ', snapshot.data().totalPopulation);
Python
collection_ref = client.collection("users") aggregate_query = aggregation.AggregationQuery(collection_ref) aggregate_query.sum("coins", alias="sum") results = aggregate_query.get() for result in results: print(f"Alias of results from query: {result[0].alias}") print(f"Sum of results from query: {result[0].value}")
शुरू करें
func createSumQuery(w io.Writer, projectID string) error { 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) aggregationQuery := query.NewAggregationQuery().WithSum("coins", "sum_coins") results, err := aggregationQuery.Get(ctx) if err != nil { return err } sum, ok := results["sum_coins"] if !ok { return errors.New("firestore: couldn't get alias for SUM from results") } sumValue := sum.(*firestorepb.Value) fmt.Fprintf(w, "Sum of results from query: %d\n", sumValue.GetIntegerValue()) return nil }
sum()
एग्रीगेशन, क्वेरी पर मौजूद किसी भी फ़िल्टर और किसी भी लिमिट वाले क्लॉज़ को ध्यान में रखता है—उदाहरण के लिए:
Web
const coll = collection(firestore, 'cities'); const q = query(coll, where('capital', '==', true)); const snapshot = await getAggregateFromServer(q, { totalPopulation: sum('population') }); console.log('totalPopulation: ', snapshot.data().totalPopulation);
Swift
let query = db.collection("cities").whereField("capital", isEqualTo: true) let aggregateQuery = query.aggregate([AggregateField.sum("population")]) do { let snapshot = try await aggregateQuery.getAggregation(source: .server) print(snapshot.get(AggregateField.sum("population"))) } catch { print(error) }
Objective-C
FIRQuery *query = [[self.db collectionWithPath:@"cities"] queryWhereFilter:[FIRFilter filterWhereField:@"capital" isEqualTo:@YES]]; FIRAggregateQuery *aggregateQuery = [query aggregate:@[ [FIRAggregateField aggregateFieldForSumOfField:@"population"]]]; [aggregateQuery aggregationWithSource:FIRAggregateSourceServer completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error fetching aggregate: %@", error); } else { NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); } }];
Java
Query query = db.collection("cities").whereEqualTo("capital", true); AggregateQuery aggregateQuery = query.aggregate(AggregateField.sum("population")); aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() { @Override public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) { if (task.isSuccessful()) { // Aggregate fetched successfully AggregateQuerySnapshot snapshot = task.getResult(); Log.d(TAG, "Sum: " + snapshot.get(AggregateField.sum("population"))); } else { Log.d(TAG, "Aggregation failed: ", task.getException()); } } });
Kotlin+KTX
val query = db.collection("cities").whereEqualTo("capital", true) val aggregateQuery = query.aggregate(AggregateField.sum("population")) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { // Aggregate fetched successfully val snapshot = task.result Log.d(TAG, "Sum: ${snapshot.get(AggregateField.sum("population"))}") } else { Log.d(TAG, "Aggregate failed: ", task.getException()) } }
Java
collection = db.collection("cities"); query = collection.whereEqualTo("state", "CA"); snapshot = query.aggregate(sum("population")).get().get(); System.out.println("Sum: " + snapshot.get(sum("population")));
Node.js के लिए
const coll = firestore.collection('cities'); const q = coll.where("capital", "==", true); const sumAggregateQuery = q.aggregate({ totalPopulation: AggregateField.sum('population'), }); const snapshot = await sumAggregateQuery.get(); console.log('totalPopulation: ', snapshot.data().totalPopulation);
Python
collection_ref = client.collection("users") query = collection_ref.where(filter=FieldFilter("people", "==", "Matthew")) aggregate_query = aggregation.AggregationQuery(query) aggregate_query.sum("coins", alias="sum") results = aggregate_query.get() for result in results: print(f"Alias of results from query: {result[0].alias}") print(f"Sum of results from query: {result[0].value}")
शुरू करें
func createSumQuery(w io.Writer, projectID string) error { 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).Limit(5) aggregationQuery := query.NewAggregationQuery().WithSum("coins", "sum_coins") results, err := aggregationQuery.Get(ctx) if err != nil { return err } sum, ok := results["sum_coins"] if !ok { return errors.New("firestore: couldn't get alias for SUM from results") } sumValue := sum.(*firestorepb.Value) fmt.Fprintf(w, "Sum of results from query: %d\n", sumValue.GetIntegerValue()) return nil }
average()
एग्रीगेशन का इस्तेमाल करना
किसी क्वेरी से मेल खाने वाली संख्या वाली वैल्यू का औसत निकालने के लिए, average()
एग्रीगेशन का इस्तेमाल करें—उदाहरण के लिए:
Web
const coll = collection(firestore, 'cities'); const snapshot = await getAggregateFromServer(coll, { averagePopulation: average('population') }); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Swift
let query = db.collection("cities") let aggregateQuery = query.aggregate([AggregateField.average("population")]) do { let snapshot = try await aggregateQuery.getAggregation(source: .server) print(snapshot.get(AggregateField.average("population"))) } catch { print(error) }
Objective-C
FIRQuery *query = [self.db collectionWithPath:@"cities"]; FIRAggregateQuery *aggregateQuery = [query aggregate:@[ [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; [aggregateQuery aggregationWithSource:FIRAggregateSourceServer completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error fetching aggregate: %@", error); } else { NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); } }];
Java
Query query = db.collection("cities"); AggregateQuery aggregateQuery = query.aggregate(AggregateField.average("population")); aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() { @Override public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) { if (task.isSuccessful()) { // Aggregate fetched successfully AggregateQuerySnapshot snapshot = task.getResult(); Log.d(TAG, "Average: " + snapshot.get(AggregateField.average("population"))); } else { Log.d(TAG, "Aggregation failed: ", task.getException()); } } });
Kotlin+KTX
val query = db.collection("cities") val aggregateQuery = query.aggregate(AggregateField.average("population")) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { // Aggregate fetched successfully val snapshot = task.result Log.d(TAG, "Average: ${snapshot.get(AggregateField.average("population"))}") } else { Log.d(TAG, "Aggregate failed: ", task.getException()) } }
Java
collection = db.collection("cities"); snapshot = collection.aggregate(average("population")).get().get(); System.out.println("Average: " + snapshot.get(average("population")));
Node.js के लिए
const coll = firestore.collection('cities'); const averageAggregateQuery = coll.aggregate({ averagePopulation: AggregateField.average('population'), }); const snapshot = await averageAggregateQuery.get(); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Python
collection_ref = client.collection("users") aggregate_query = aggregation.AggregationQuery(collection_ref) aggregate_query.avg("coins", alias="avg") results = aggregate_query.get() for result in results: print(f"Alias of results from query: {result[0].alias}") print(f"Average of results from query: {result[0].value}")
शुरू करें
func createAvgQuery(w io.Writer, projectID string) error { 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) aggregationQuery := query.NewAggregationQuery().WithAvg("coins", "avg_coins") results, err := aggregationQuery.Get(ctx) if err != nil { return err } avg, ok := results["avg_coins"] if !ok { return errors.New("firestore: couldn't get alias for AVG from results") } avgValue := avg.(*firestorepb.Value) fmt.Fprintf(w, "Avg of results from query: %d\n", avgValue.GetDoubleValue()) return nil }
average()
एग्रीगेशन, क्वेरी पर मौजूद किसी भी फ़िल्टर और किसी भी सीमा वाले क्लॉज़ को ध्यान में रखता है—उदाहरण के लिए:
Web
const coll = collection(firestore, 'cities'); const q = query(coll, where('capital', '==', true)); const snapshot = await getAggregateFromServer(q, { averagePopulation: average('population') }); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Swift
let query = db.collection("cities").whereField("capital", isEqualTo: true) let aggregateQuery = query.aggregate([AggregateField.average("population")]) do { let snapshot = try await aggregateQuery.getAggregation(source: .server) print(snapshot.get(AggregateField.average("population"))) } catch { print(error) }
Objective-C
FIRQuery *query = [[self.db collectionWithPath:@"cities"] queryWhereFilter:[FIRFilter filterWhereField:@"capital" isEqualTo:@YES]]; FIRAggregateQuery *aggregateQuery = [query aggregate:@[ [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; [aggregateQuery aggregationWithSource:FIRAggregateSourceServer completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error fetching aggregate: %@", error); } else { NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); } }];
Java
Query query = db.collection("cities").whereEqualTo("capital", true); AggregateQuery aggregateQuery = query.aggregate(AggregateField.average("population")); aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() { @Override public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) { if (task.isSuccessful()) { // Aggregate fetched successfully AggregateQuerySnapshot snapshot = task.getResult(); Log.d(TAG, "Average: " + snapshot.get(AggregateField.average("population"))); } else { Log.d(TAG, "Aggregation failed: ", task.getException()); } } });
Kotlin+KTX
val query = db.collection("cities").whereEqualTo("capital", true) val aggregateQuery = query.aggregate(AggregateField.average("population")) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { // Aggregate fetched successfully val snapshot = task.result Log.d(TAG, "Average: ${snapshot.get(AggregateField.average("population"))}") } else { Log.d(TAG, "Aggregate failed: ", task.getException()) } }
Java
collection = db.collection("cities"); query = collection.whereEqualTo("state", "CA"); snapshot = query.aggregate(average("population")).get().get(); System.out.println("Average: " + snapshot.get(average("population")));
Node.js के लिए
const coll = firestore.collection('cities'); const q = coll.where("capital", "==", true); const averageAggregateQuery = q.aggregate({ averagePopulation: AggregateField.average('population'), }); const snapshot = await averageAggregateQuery.get(); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Python
collection_ref = client.collection("users") query = collection_ref.where(filter=FieldFilter("people", "==", "Matthew")) aggregate_query = aggregation.AggregationQuery(query) aggregate_query.avg("coins", alias="avg") results = aggregate_query.get() for result in results: print(f"Alias of results from query: {result[0].alias}") print(f"Average of results from query: {result[0].value}")
शुरू करें
func createAvgQuery(w io.Writer, projectID string) error { 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).Limit(5) aggregationQuery := query.NewAggregationQuery().WithAvg("coins", "avg_coins") results, err := aggregationQuery.Get(ctx) if err != nil { return err } avg, ok := results["avg_coins"] if !ok { return errors.New("firestore: couldn't get alias for AVG from results") } avgValue := avg.(*firestorepb.Value) fmt.Fprintf(w, "Avg of results from query: %d\n", avgValue.GetDoubleValue()) return nil }
किसी क्वेरी में एक से ज़्यादा एग्रीगेशन की गणना करना
किसी एक एग्रीगेशन पाइपलाइन में कई एग्रीगेशन को मिलाया जा सकता है. इससे इंडेक्स रीड की ज़रूरी संख्या कम हो सकती है. अगर क्वेरी में एक से ज़्यादा फ़ील्ड पर एग्रीगेशन शामिल हैं, तो क्वेरी के लिए कंपोज़िट इंडेक्स की ज़रूरत हो सकती है. ऐसे में, Cloud Firestore एक इंडेक्स का सुझाव देता है.
यहां दिया गया उदाहरण, एक एग्रीगेशन क्वेरी में एक से ज़्यादा एग्रीगेशन करता है:
Web
const coll = collection(firestore, 'cities'); const snapshot = await getAggregateFromServer(coll, { countOfDocs: count(), totalPopulation: sum('population'), averagePopulation: average('population') }); console.log('countOfDocs: ', snapshot.data().countOfDocs); console.log('totalPopulation: ', snapshot.data().totalPopulation); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Swift
let query = db.collection("cities") let aggregateQuery = query.aggregate([ AggregateField.count(), AggregateField.sum("population"), AggregateField.average("population")]) do { let snapshot = try await aggregateQuery.getAggregation(source: .server) print("Count: \(snapshot.get(AggregateField.count()))") print("Sum: \(snapshot.get(AggregateField.sum("population")))") print("Average: \(snapshot.get(AggregateField.average("population")))") } catch { print(error) }
Objective-C
FIRQuery *query = [self.db collectionWithPath:@"cities"]; FIRAggregateQuery *aggregateQuery = [query aggregate:@[ [FIRAggregateField aggregateFieldForCount], [FIRAggregateField aggregateFieldForSumOfField:@"population"], [FIRAggregateField aggregateFieldForAverageOfField:@"population"]]]; [aggregateQuery aggregationWithSource:FIRAggregateSourceServer completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) { if (error != nil) { NSLog(@"Error fetching aggregate: %@", error); } else { NSLog(@"Count: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForCount]]); NSLog(@"Sum: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForSumOfField:@"population"]]); NSLog(@"Avg: %@", [snapshot valueForAggregateField:[FIRAggregateField aggregateFieldForAverageOfField:@"population"]]); } }];
Java
Query query = db.collection("cities"); AggregateQuery aggregateQuery = query.aggregate( AggregateField.count(), AggregateField.sum("population"), AggregateField.average("population")); aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener(new OnCompleteListener<AggregateQuerySnapshot>() { @Override public void onComplete(@NonNull Task<AggregateQuerySnapshot> task) { if (task.isSuccessful()) { // Aggregate fetched successfully AggregateQuerySnapshot snapshot = task.getResult(); Log.d(TAG, "Count: " + snapshot.get(AggregateField.count())); Log.d(TAG, "Sum: " + snapshot.get(AggregateField.sum("population"))); Log.d(TAG, "Average: " + snapshot.get(AggregateField.average("population"))); } else { Log.d(TAG, "Aggregation failed: ", task.getException()); } } });
Kotlin+KTX
val query = db.collection("cities") val aggregateQuery = query.aggregate( AggregateField.count(), AggregateField.sum("population"), AggregateField.average("population") ) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { // Aggregate fetched successfully val snapshot = task.result Log.d(TAG, "Count: ${snapshot.get(AggregateField.count())}") Log.d(TAG, "Sum: ${snapshot.get(AggregateField.sum("population"))}") Log.d(TAG, "Average: ${snapshot.get(AggregateField.average("population"))}") } else { Log.d(TAG, "Aggregate failed: ", task.getException()) } }
Java
collection = db.collection("cities"); query = collection.whereEqualTo("state", "CA"); AggregateQuery aggregateQuery = query.aggregate(count(), sum("population"), average("population")); snapshot = aggregateQuery.get().get(); System.out.println("Count: " + snapshot.getCount()); System.out.println("Sum: " + snapshot.get(sum("population"))); System.out.println("Average: " + snapshot.get(average("population")));
Node.js के लिए
const coll = firestore.collection('cities'); const aggregateQuery = coll.aggregate({ countOfDocs: AggregateField.count(), totalPopulation: AggregateField.sum('population'), averagePopulation: AggregateField.average('population') }); const snapshot = await aggregateQuery.get(); console.log('countOfDocs: ', snapshot.data().countOfDocs); console.log('totalPopulation: ', snapshot.data().totalPopulation); console.log('averagePopulation: ', snapshot.data().averagePopulation);
Python
collection_ref = client.collection("users") query = collection_ref.where(filter=FieldFilter("people", "==", "Matthew")) aggregate_query = aggregation.AggregationQuery(query) aggregate_query.sum("coins", alias="sum").avg("coins", alias="avg") results = aggregate_query.get() for result in results: print(f"Alias of results from query: {result[0].alias}") print(f"Aggregation of results from query: {result[0].value}")
शुरू करें
func createMultiAggregationQuery(w io.Writer, projectID string) error { 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) aggregationQuery := query.NewAggregationQuery().WithCount("count").WithSum("coins", "sum_coins").WithAvg("coins", "avg_coins") results, err := aggregationQuery.Get(ctx) if err != nil { return err } }
एक से ज़्यादा एग्रीगेशन वाली क्वेरी में सिर्फ़ वे दस्तावेज़ शामिल होते हैं जिनमें हर एग्रीगेशन के सभी फ़ील्ड होते हैं. इस वजह से, हर एग्रीगेशन को अलग-अलग करने के नतीजे अलग-अलग हो सकते हैं.
एग्रीगेशन क्वेरी के लिए सुरक्षा के नियम
Cloud Firestore के सुरक्षा नियम, एग्रीगेशन क्वेरी पर वैसे ही काम करते हैं जैसे दस्तावेज़ सबमिट करने वाली क्वेरी पर. दूसरे शब्दों में, अगर आपके नियम क्लाइंट को किसी कलेक्शन या कलेक्शन ग्रुप की क्वेरी चलाने की अनुमति देते हैं, तो क्लाइंट उन क्वेरी के लिए एग्रीगेशन भी कर सकते हैं. इस बारे में ज़्यादा जानें कि Cloud Firestore के सुरक्षा नियम क्वेरी के साथ कैसे इंटरैक्ट करते हैं.
व्यवहार और सीमाएं
एग्रीगेशन क्वेरी के साथ काम करते समय इन व्यवहार और सीमाओं का ध्यान रखें:
रीयल-टाइम लिसनर और ऑफ़लाइन क्वेरी के साथ एग्रीगेशन क्वेरी का इस्तेमाल नहीं किया जा सकता. एग्रीगेशन क्वेरी सिर्फ़ डायरेक्ट सर्वर रिस्पॉन्स से काम करती हैं. क्वेरी को सिर्फ़ Cloud Firestore बैकएंड से दिखाया जाता है. इसमें लोकल कैश मेमोरी और बफ़र किए गए अपडेट को छोड़कर आगे बढ़ा दिया जाता है. यह व्यवहार, Cloud Firestore लेन-देन में किए जाने वाले ऑपरेशन के जैसा है.
अगर कोई एग्रीगेशन 60 सेकंड के अंदर ठीक नहीं हो पाता है, तो यह
DEADLINE_EXCEEDED
गड़बड़ी दिखाता है. परफ़ॉर्मेंस, आपके इंडेक्स कॉन्फ़िगरेशन और डेटासेट के साइज़ पर निर्भर करती है.अगर कार्रवाई को 60 सेकंड के अंदर पूरा नहीं किया जा सकता, तो बड़े डेटासेट के लिए काउंटर का इस्तेमाल करना एक संभावित समाधान है.
एग्रीगेशन क्वेरी, इंडेक्स एंट्री से पढ़ी जाती हैं. इनमें सिर्फ़ इंडेक्स किए गए फ़ील्ड शामिल होते हैं.
एग्रीगेशन क्वेरी में
OrderBy
क्लॉज़ जोड़ने से, ऐसे दस्तावेज़ों का एग्रीगेशन सीमित हो जाता है जहां क्रम से लगाने का फ़ील्ड मौजूद है.sum()
औरaverage()
एग्रीगेशन के लिए, बिना संख्या वाली वैल्यू को अनदेखा किया जाता है.sum()
औरaverage()
एग्रीगेशन, सिर्फ़ पूर्णांक की वैल्यू और फ़्लोटिंग-पॉइंट नंबर की वैल्यू पर ध्यान देते हैं.किसी क्वेरी में कई एग्रीगेशन को मिलाते समय ध्यान रखें कि
sum()
औरaverage()
बिना संख्या वाली वैल्यू को अनदेखा करते हैं, जबकिcount()
में बिना संख्या वाली वैल्यू शामिल होती हैं.अगर अलग-अलग फ़ील्ड में एग्रीगेशन को जोड़ा जाता है, तो कैलकुलेशन में सिर्फ़ उन दस्तावेज़ों को शामिल किया जाता है जिनमें वे सभी फ़ील्ड मौजूद हैं.
कीमत
एग्रीगेशन क्वेरी की कीमत, क्वेरी से मेल खाने वाली इंडेक्स एंट्री की संख्या के हिसाब से तय होती है. ज़्यादा संख्या में मेल खाने वाली एंट्री के लिए, आपसे कुछ डेटा पढ़ने का शुल्क लिया जाता है.
ज़्यादा जानकारी के लिए, कीमत की जानकारी देखें.