تتيح لك طلبات البحث في 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
do { let snapshot = try await db.collection("restaurants") .document("arinell-pizza") .collection("ratings") .getDocuments() print(snapshot) } catch { print(error) }
Objective-C
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 };
Swift
struct Restaurant { let name: String let avgRating: Float let numRatings: Int } let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683)
Objective-C
@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 }); }); }); }
Swift
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
- (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، والذي إلى زيادة التكاليف. لمزيد من المعلومات، يُرجى الاطّلاع على صفحة أسعار Cloud Functions.
- وقت الاستجابة: من خلال نقل تجميع البيانات إلى إحدى وظائف السحابة الإلكترونية، لن يتمكّن التطبيق من الاطّلاع على البيانات المعدّلة إلى أن تكتمل وظيفة السحابة الإلكترونية. قيد التنفيذ وتم إعلام العميل بالبيانات الجديدة. استنادًا إلى سرعة وظيفة السحابة الإلكترونية، فقد يستغرق ذلك وقتًا أطول من تنفيذ على الجهاز.
- معدلات الكتابة: قد لا يعمل هذا الحلّ مع عمليات التجميع التي يتم تعديلها بشكل متكرّر لأنّه لا يمكن تعديل مستندات Cloud Firestore إلا مرة واحدة في الثانية بحد أقصى. بالإضافة إلى ذلك، إذا قرأت المعاملة مستندًا إذا تم تعديلها خارج إطار المعاملة، فتُعيد المحاولة لعدد محدود من المرات ثم تفشل. راجِع العدّادات الموزعة. للعثور على حل بديل ملائم لعمليات التجميع التي تحتاج إلى مزيد من التحديثات المتكررة.