مجموعات وقت الكتابة

تتيح لك الاستعلامات في Cloud Firestore العثور على المستندات في مجموعات كبيرة. للحصول على نظرة ثاقبة لخصائص المجموعة ككل، يمكنك تجميع البيانات عبر مجموعة.

يمكنك تجميع البيانات إما في وقت القراءة أو في وقت الكتابة:

  • تقوم مجموعات وقت القراءة بحساب النتيجة في وقت الطلب. يدعم Cloud Firestore استعلامات التجميع count() و sum() و average() في وقت القراءة. من الأسهل إضافة استعلامات تجميع وقت القراءة إلى تطبيقك مقارنة بتجميعات وقت الكتابة. لمزيد من المعلومات حول استعلامات التجميع، راجع تلخيص البيانات باستخدام استعلامات التجميع .

  • تقوم مجموعات وقت الكتابة بحساب نتيجة في كل مرة يقوم فيها التطبيق بعملية كتابة ذات صلة. تعد تجميعات وقت الكتابة بمثابة عمل أكثر يجب تنفيذه، ولكن يمكنك استخدامها بدلاً من تجميعات وقت القراءة لأحد الأسباب التالية:

    • تريد الاستماع إلى نتيجة التجميع للحصول على التحديثات في الوقت الحقيقي. لا تدعم استعلامات التجميع count() و sum() و average() التحديثات في الوقت الفعلي.
    • تريد تخزين نتيجة التجميع في ذاكرة التخزين المؤقت من جانب العميل. لا تدعم استعلامات التجميع count() و sum() و average() التخزين المؤقت.
    • أنت تقوم بتجميع البيانات من عشرات الآلاف من المستندات لكل مستخدم لديك وتأخذ في الاعتبار التكاليف. عند عدد أقل من المستندات، تكون تكلفة تجميعات وقت القراءة أقل. بالنسبة لعدد كبير من المستندات في مجموعات، قد تكون تكلفة تجميعات وقت الكتابة أقل.

يمكنك تنفيذ تجميع وقت الكتابة باستخدام معاملة من جانب العميل أو باستخدام Cloud Functions. تصف الأقسام التالية كيفية تنفيذ تجميعات وقت الكتابة.

الحل: تجميع وقت الكتابة مع معاملة من جانب العميل

فكر في تطبيق توصيات محلية يساعد المستخدمين في العثور على مطاعم رائعة. يسترد الاستعلام التالي جميع التقييمات لمطعم معين:

ويب

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

سويفت

ملاحظة: هذا المنتج غير متوفر في أنظمة watchOS وApp Clip.
do {
  let snapshot = try await db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .getDocuments()
  print(snapshot)
} catch {
  print(error)
}

ج موضوعية

ملاحظة: هذا المنتج غير متوفر في أنظمة watchOS وApp Clip.
FIRQuery *query = [[[self.db collectionWithPath:@"restaurants"]
    documentWithPath:@"arinell-pizza"] collectionWithPath:@"ratings"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                    NSError * _Nullable error) {
  // ...
}];

Kotlin+KTX

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
};

سويفت

ملاحظة: هذا المنتج غير متوفر في أنظمة 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)

ج موضوعية

ملاحظة: هذا المنتج غير متوفر في أنظمة 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+KTX

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 });
        });
    });
}

سويفت

ملاحظة: هذا المنتج غير متوفر في أنظمة 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 {
    // ...
  }
}

ج موضوعية

ملاحظة: هذا المنتج غير متوفر في أنظمة 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+KTX

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

إذا كانت المعاملات من جانب العميل غير مناسبة لتطبيقك، فيمكنك استخدام وظيفة السحابة لتحديث المعلومات المجمعة في كل مرة تتم فيها إضافة تقييم جديد إلى المطعم:

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 Firestore إلا مرة واحدة في الثانية على الأكثر. بالإضافة إلى ذلك، إذا قرأت إحدى المعاملات مستندًا تم تعديله خارج المعاملة، فإنها تعيد المحاولة لعدد محدود من المرات ثم تفشل. تحقق من العدادات الموزعة بحثًا عن حل بديل للتجميعات التي تحتاج إلى تحديثات أكثر تكرارًا.