लिखने के समय का एग्रीगेशन

Cloud Firestore में क्वेरी की मदद से, बड़े कलेक्शन में मौजूद दस्तावेज़ों को खोजा जा सकता है. कलेक्शन की सभी प्रॉपर्टी के बारे में जानकारी पाने के लिए, कलेक्शन में मौजूद डेटा को इकट्ठा किया जा सकता है.

डेटा को पढ़ते समय या लिखते समय इकट्ठा किया जा सकता है:

  • पढ़ते समय डेटा इकट्ठा करने की सुविधा की मदद से, अनुरोध के समय नतीजे की गिनती की जाती है. Cloud Firestore में, पढ़ते समय count(), sum(), और average() क्वेरी की मदद से डेटा इकट्ठा किया जा सकता है. पढ़ते समय डेटा इकट्ठा करने की क्वेरी को, लिखते समय डेटा इकट्ठा करने की क्वेरी के मुकाबले अपने ऐप्लिकेशन में आसानी से जोड़ा जा सकता है. डेटा इकट्ठा करने की क्वेरी के बारे में ज़्यादा जानने के लिए, डेटा को इकट्ठा करने की क्वेरी की मदद से खास जानकारी पाना लेख पढ़ें.

  • लिखते समय डेटा इकट्ठा करने की सुविधा की मदद से, ऐप्लिकेशन के हर बार काम की कोई जानकारी लिखने पर नतीजे की गिनती की जाती है. लिखते समय डेटा इकट्ठा करने की सुविधा को लागू करने में ज़्यादा मेहनत लगती है. हालांकि, इसे इन वजहों से, पढ़ते समय डेटा इकट्ठा करने की सुविधा के बजाय इस्तेमाल किया जा सकता है:

    • आपको रीयल-टाइम अपडेट के लिए, डेटा इकट्ठा करने के नतीजे को सुनना है. count(), sum(), और average() क्वेरी की मदद से डेटा इकट्ठा करने पर, रीयल-टाइम अपडेट नहीं मिलते.
    • आपको डेटा इकट्ठा करने के नतीजे को क्लाइंट-साइड कैश में सेव करना है. count(), sum(), और average() क्वेरी की मदद से डेटा इकट्ठा करने पर, कैशिंग की सुविधा नहीं मिलती.
    • आपको अपने हर उपयोगकर्ता के लिए, हज़ारों दस्तावेज़ों से डेटा इकट्ठा करना है और आपको लागत के बारे में भी सोचना है. कम दस्तावेज़ों के लिए, पढ़ते समय डेटा इकट्ठा करने की सुविधा का इस्तेमाल करने पर कम लागत लगती है. डेटा इकट्ठा करने के लिए, ज़्यादा दस्तावेज़ों के लिए लिखते समय डेटा इकट्ठा करने की सुविधा का इस्तेमाल करने पर कम लागत लग सकती है.

लिखते समय डेटा इकट्ठा करने की सुविधा को, क्लाइंट-साइड लेन-देन या Cloud Functionsकी मदद से लागू किया जा सकता है. लिखते समय डेटा इकट्ठा करने की सुविधा को लागू करने का तरीका जानने के लिए, यहां दिया गया सेक्शन पढ़ें.

तरीका: क्लाइंट-साइड लेन-देन की मदद से, लिखते समय डेटा इकट्ठा करना

मान लें कि आपके पास स्थानीय सुझाव देने वाला कोई ऐप्लिकेशन है, जो उपयोगकर्ताओं को अच्छे रेस्टोरेंट ढूंढने में मदद करता है. यहां दी गई क्वेरी, किसी रेस्टोरेंट के लिए सभी रेटिंग वापस लाती है:

वेब

db.collection("restaurants")
  .doc("arinell-pizza")
  .collection("ratings")
  .get();

Swift

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
do {
  let snapshot = try await db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .getDocuments()
  print(snapshot)
} catch {
  print(error)
}

Objective-C

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
FIRQuery *query = [[[self.db collectionWithPath:@"restaurants"]
    documentWithPath:@"arinell-pizza"] collectionWithPath:@"ratings"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                    NSError * _Nullable error) {
  // ...
}];

Kotlin

db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .get()

Java

db.collection("restaurants")
        .document("arinell-pizza")
        .collection("ratings")
        .get();

सभी रेटिंग फ़ेच करने और फिर इकट्ठा की गई जानकारी कंप्यूट करने के बजाय, हम इस जानकारी को रेस्टोरेंट के दस्तावेज़ में ही सेव कर सकते हैं:

वेब

var arinellDoc = {
  name: 'Arinell Pizza',
  avgRating: 4.65,
  numRatings: 683
};

Swift

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
struct Restaurant {

  let name: String
  let avgRating: Float
  let numRatings: Int

}

let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683)

Objective-C

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
@interface FIRRestaurant : NSObject

@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) float averageRating;
@property (nonatomic, readonly) NSInteger ratingCount;

- (instancetype)initWithName:(NSString *)name
               averageRating:(float)averageRating
                 ratingCount:(NSInteger)ratingCount;

@end

@implementation FIRRestaurant

- (instancetype)initWithName:(NSString *)name
               averageRating:(float)averageRating
                 ratingCount:(NSInteger)ratingCount {
  self = [super init];
  if (self != nil) {
    _name = name;
    _averageRating = averageRating;
    _ratingCount = ratingCount;
  }
  return self;
}

@end

Kotlin

data class Restaurant(
    // default values required for use with "toObject"
    internal var name: String = "",
    internal var avgRating: Double = 0.0,
    internal var numRatings: Int = 0,
)
val arinell = Restaurant("Arinell Pizza", 4.65, 683)

Java

public class Restaurant {
    String name;
    double avgRating;
    int numRatings;

    public Restaurant(String name, double avgRating, int numRatings) {
        this.name = name;
        this.avgRating = avgRating;
        this.numRatings = numRatings;
    }
}
Restaurant arinell = new Restaurant("Arinell Pizza", 4.65, 683);

डेटा इकट्ठा करने की इन सुविधाओं को एक जैसा बनाए रखने के लिए, सब कलेक्शन में नई रेटिंग जोड़े जाने पर इन्हें अपडेट करना ज़रूरी है. एक जैसा डेटा बनाए रखने के लिए, एक ही लेन-देन में डेटा जोड़ने और अपडेट करने की कार्रवाई की जा सकती है:

वेब

function addRating(restaurantRef, rating) {
    // Create a reference for a new rating, for use inside the transaction
    var ratingRef = restaurantRef.collection('ratings').doc();

    // In a transaction, add the new rating and update the aggregate totals
    return db.runTransaction((transaction) => {
        return transaction.get(restaurantRef).then((res) => {
            if (!res.exists) {
                throw "Document does not exist!";
            }

            // Compute new number of ratings
            var newNumRatings = res.data().numRatings + 1;

            // Compute new average rating
            var oldRatingTotal = res.data().avgRating * res.data().numRatings;
            var newAvgRating = (oldRatingTotal + rating) / newNumRatings;

            // Commit to Firestore
            transaction.update(restaurantRef, {
                numRatings: newNumRatings,
                avgRating: newAvgRating
            });
            transaction.set(ratingRef, { rating: rating });
        });
    });
}

Swift

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
func addRatingTransaction(restaurantRef: DocumentReference, rating: Float) async {
  let ratingRef: DocumentReference = restaurantRef.collection("ratings").document()

  do {
    let _ = try await db.runTransaction({ (transaction, errorPointer) -> Any? in
      do {
        let restaurantDocument = try transaction.getDocument(restaurantRef).data()
        guard var restaurantData = restaurantDocument else { return nil }

        // Compute new number of ratings
        let numRatings = restaurantData["numRatings"] as! Int
        let newNumRatings = numRatings + 1

        // Compute new average rating
        let avgRating = restaurantData["avgRating"] as! Float
        let oldRatingTotal = avgRating * Float(numRatings)
        let newAvgRating = (oldRatingTotal + rating) / Float(newNumRatings)

        // Set new restaurant info
        restaurantData["numRatings"] = newNumRatings
        restaurantData["avgRating"] = newAvgRating

        // Commit to Firestore
        transaction.setData(restaurantData, forDocument: restaurantRef)
        transaction.setData(["rating": rating], forDocument: ratingRef)
      } catch {
        // Error getting restaurant data
        // ...
      }

      return nil
    })
  } catch {
    // ...
  }
}

Objective-C

ध्यान दें: यह प्रॉडक्ट, watchOS और App Clip टारगेट पर उपलब्ध नहीं है.
- (void)addRatingTransactionWithRestaurantReference:(FIRDocumentReference *)restaurant
                                             rating:(float)rating {
  FIRDocumentReference *ratingReference =
      [[restaurant collectionWithPath:@"ratings"] documentWithAutoID];

  [self.db runTransactionWithBlock:^id (FIRTransaction *transaction,
                                        NSError **errorPointer) {
    FIRDocumentSnapshot *restaurantSnapshot =
        [transaction getDocument:restaurant error:errorPointer];

    if (restaurantSnapshot == nil) {
      return nil;
    }

    NSMutableDictionary *restaurantData = [restaurantSnapshot.data mutableCopy];
    if (restaurantData == nil) {
      return nil;
    }

    // Compute new number of ratings
    NSInteger ratingCount = [restaurantData[@"numRatings"] integerValue];
    NSInteger newRatingCount = ratingCount + 1;

    // Compute new average rating
    float averageRating = [restaurantData[@"avgRating"] floatValue];
    float newAverageRating = (averageRating * ratingCount + rating) / newRatingCount;

    // Set new restaurant info

    restaurantData[@"numRatings"] = @(newRatingCount);
    restaurantData[@"avgRating"] = @(newAverageRating);

    // Commit to Firestore
    [transaction setData:restaurantData forDocument:restaurant];
    [transaction setData:@{@"rating": @(rating)} forDocument:ratingReference];
    return nil;
  } completion:^(id  _Nullable result, NSError * _Nullable error) {
    // ...
  }];
}

Kotlin

private fun addRating(restaurantRef: DocumentReference, rating: Float): Task<Void> {
    // Create reference for new rating, for use inside the transaction
    val ratingRef = restaurantRef.collection("ratings").document()

    // In a transaction, add the new rating and update the aggregate totals
    return db.runTransaction { transaction ->
        val restaurant = transaction.get(restaurantRef).toObject<Restaurant>()!!

        // Compute new number of ratings
        val newNumRatings = restaurant.numRatings + 1

        // Compute new average rating
        val oldRatingTotal = restaurant.avgRating * restaurant.numRatings
        val newAvgRating = (oldRatingTotal + rating) / newNumRatings

        // Set new restaurant info
        restaurant.numRatings = newNumRatings
        restaurant.avgRating = newAvgRating

        // Update restaurant
        transaction.set(restaurantRef, restaurant)

        // Update rating
        val data = hashMapOf<String, Any>(
            "rating" to rating,
        )
        transaction.set(ratingRef, data, SetOptions.merge())

        null
    }
}

Java

private Task<Void> addRating(final DocumentReference restaurantRef, final float rating) {
    // Create reference for new rating, for use inside the transaction
    final DocumentReference ratingRef = restaurantRef.collection("ratings").document();

    // In a transaction, add the new rating and update the aggregate totals
    return db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
            Restaurant restaurant = transaction.get(restaurantRef).toObject(Restaurant.class);

            // Compute new number of ratings
            int newNumRatings = restaurant.numRatings + 1;

            // Compute new average rating
            double oldRatingTotal = restaurant.avgRating * restaurant.numRatings;
            double newAvgRating = (oldRatingTotal + rating) / newNumRatings;

            // Set new restaurant info
            restaurant.numRatings = newNumRatings;
            restaurant.avgRating = newAvgRating;

            // Update restaurant
            transaction.set(restaurantRef, restaurant);

            // Update rating
            Map<String, Object> data = new HashMap<>();
            data.put("rating", rating);
            transaction.set(ratingRef, data, SetOptions.merge());

            return null;
        }
    });
}

लेन-देन का इस्तेमाल करने से, इकट्ठा किया गया डेटा, कलेक्शन के डेटा के साथ एक जैसा बना रहता है. Cloud Firestore में लेन-देन के बारे में ज़्यादा जानने के लिए, लेन-देन और बैच में डेटा लिखना लेख पढ़ें.

सीमाएं

ऊपर दिखाया गया तरीका, Cloud Firestore क्लाइंट लाइब्रेरी का इस्तेमाल करके डेटा इकट्ठा करने के बारे में बताता है. हालांकि, आपको इन सीमाओं के बारे में पता होना चाहिए:

  • सुरक्षा - क्लाइंट-साइड लेन-देन के लिए, क्लाइंट को अपने डेटाबेस में इकट्ठा किए गए डेटा को अपडेट करने की अनुमति देनी होगी. सुरक्षा के बेहतर नियम लिखकर, इस तरीके से जुड़े जोखिमों को कम किया जा सकता है. हालांकि, यह हर स्थिति में सही नहीं हो सकता.
  • ऑफ़लाइन होने पर भी काम करने की सुविधा - जब उपयोगकर्ता का डिवाइस ऑफ़लाइन होगा, तब क्लाइंट-साइड लेन-देन पूरा नहीं हो पाएगा. इसका मतलब है कि आपको अपने ऐप्लिकेशन में इस स्थिति को मैनेज करना होगा और सही समय पर फिर से कोशिश करनी होगी.
  • परफ़ॉर्मेंस - अगर आपके लेन-देन में, डेटा पढ़ने, लिखने, और अपडेट करने की कई कार्रवाइयां शामिल हैं, तो Cloud Firestore बैकएंड पर कई अनुरोध भेजने पड़ सकते हैं. मोबाइल डिवाइस पर, इसमें काफ़ी समय लग सकता है.
  • डेटा लिखने की दरें - यह तरीका, अक्सर अपडेट किए जाने वाले डेटा के लिए काम नहीं कर सकता. ऐसा इसलिए है, क्योंकि Cloud Firestore के दस्तावेज़ों को हर सेकंड में सिर्फ़ एक बार अपडेट किया जा सकता है. इसके अलावा, अगर कोई लेन-देन किसी ऐसे दस्तावेज़ को पढ़ता है जिसे लेन-देन के बाहर जाकर बदला गया है, तो वह कुछ बार फिर से कोशिश करता है और फिर पूरा नहीं हो पाता. डेटा इकट्ठा करने के लिए, डिस्ट्रिब्यूटेड काउंटर देखें. इससे, अक्सर अपडेट किए जाने वाले डेटा को इकट्ठा करने में मदद मिलती है.

तरीका: Cloud Functions की मदद से, लिखते समय डेटा इकट्ठा करना

अगर क्लाइंट-साइड लेन-देन आपके ऐप्लिकेशन के लिए सही नहीं हैं, तो Cloud Function का इस्तेमाल करके, रेस्टोरेंट में नई रेटिंग जोड़े जाने पर इकट्ठा की गई जानकारी को अपडेट किया जा सकता है:

Node.js

exports.aggregateRatings = functions.firestore
    .document('restaurants/{restId}/ratings/{ratingId}')
    .onWrite(async (change, context) => {
      // Get value of the newly added rating
      const ratingVal = change.after.data().rating;

      // Get a reference to the restaurant
      const restRef = db.collection('restaurants').doc(context.params.restId);

      // Update aggregations in a transaction
      await db.runTransaction(async (transaction) => {
        const restDoc = await transaction.get(restRef);

        // Compute new number of ratings
        const newNumRatings = restDoc.data().numRatings + 1;

        // Compute new average rating
        const oldRatingTotal = restDoc.data().avgRating * restDoc.data().numRatings;
        const newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;

        // Update restaurant info
        transaction.update(restRef, {
          avgRating: newAvgRating,
          numRatings: newNumRatings
        });
      });
    });

इस तरीके में, क्लाइंट का काम होस्ट किए गए फ़ंक्शन को सौंप दिया जाता है. इसका मतलब है कि आपका मोबाइल ऐप्लिकेशन, लेन-देन पूरा होने का इंतज़ार किए बिना रेटिंग जोड़ सकता है. Cloud Function में एक्ज़ीक्यूट किया गया कोड, सुरक्षा के नियमों से बंधा नहीं होता. इसका मतलब है कि अब आपको क्लाइंट को इकट्ठा किए गए डेटा को लिखने की अनुमति देने की ज़रूरत नहीं है.

सीमाएं

डेटा इकट्ठा करने के लिए Cloud Function का इस्तेमाल करने से, क्लाइंट-साइड लेन-देन से जुड़ी कुछ समस्याएं हल हो जाती हैं. हालांकि, इसकी कुछ सीमाएं भी हैं:

  • लागत - हर रेटिंग जोड़े जाने पर, Cloud Function को कॉल किया जाएगा. इससे आपकी लागत बढ़ सकती है. ज़्यादा जानकारी के लिए, Cloud Functions कीमतें पेज देखें.
  • लेटेंसी - डेटा इकट्ठा करने का काम Cloud Function को सौंपने पर, आपका ऐप्लिकेशन अपडेट किया गया डेटा तब तक नहीं देख पाएगा, जब तक Cloud Function का एक्ज़ीक्यूशन पूरा नहीं हो जाता और क्लाइंट को नए डेटा के बारे में सूचना नहीं मिल जाती. Cloud Function की स्पीड के आधार पर, इसमें लेन-देन को स्थानीय तौर पर एक्ज़ीक्यूट करने से ज़्यादा समय लग सकता है.
  • डेटा लिखने की दरें - यह तरीका, अक्सर अपडेट किए जाने वाले डेटा के लिए काम नहीं कर सकता. ऐसा इसलिए है, क्योंकि Cloud Firestore के दस्तावेज़ों को हर सेकंड में सिर्फ़ एक बार अपडेट किया जा सकता है. इसके अलावा, अगर कोई लेन-देन किसी ऐसे दस्तावेज़ को पढ़ता है जिसे लेन-देन के बाहर जाकर बदला गया है, तो वह कुछ बार फिर से कोशिश करता है और फिर पूरा नहीं हो पाता. डेटा इकट्ठा करने के लिए, डिस्ट्रिब्यूटेड काउंटर देखें. इससे, अक्सर अपडेट किए जाने वाले डेटा को इकट्ठा करने में मदद मिलती है.