تتيح لك الاستعلامات في Cloud Firestore العثور على المستندات في مجموعات كبيرة. للحصول على رؤية حول خصائص المجموعة ككل، يمكنك تجميع البيانات عبر مجموعة.
يمكنك تجميع البيانات إما في وقت القراءة أو في وقت الكتابة:
تحسب عمليات تجميع البيانات في وقت القراءة نتيجة في وقت الطلب. تتوافق Cloud Firestore مع طلبات بحث التجميع
count()
وsum()
وaverage()
في وقت القراءة. من الأسهل إضافة طلبات بحث تجميع وقت القراءة إلى تطبيقك من تجميعات الوقت الكتابة. لمزيد من المعلومات حول طلبات البحث عن التجميع، يُرجى الاطّلاع على تلخيص البيانات باستخدام طلبات البحث عن التجميع.تحسب تجميعات وقت الكتابة نتيجة في كل مرة يُجري فيها التطبيق عملية كتابة ذات صلة. تُعد تجميعات وقت الكتابة مزيدًا من العمل لتنفيذها، ولكن يمكنك استخدامها بدلاً من تجميعات وقت القراءة لأحد الأسباب التالية:
- تريد الاستماع إلى نتيجة التجميع للاطّلاع على تعديلات في الوقت الفعلي.
لا تتيح طلبات البحث الخاصة بالتجميع
count()
وsum()
وaverage()
إجراء تعديلات في الوقت الفعلي. - وتريد تخزين نتيجة التجميع في ذاكرة تخزين مؤقت من جهة العميل.
لا تتيح طلبات البحث الخاصة بالتجميع
count()
وsum()
وaverage()
التخزين المؤقت. - أنت تقوم بتجميع البيانات من عشرات الآلاف من الوثائق لكل من المستخدمين لديك وتأخذ في الاعتبار التكاليف. مع عدد أقل من المستندات، تكون تجميعات وقت القراءة أقل. بالنسبة إلى عدد كبير من المستندات في المجموعات، قد تكون تجميعات وقت الكتابة أقل تكلفة.
- تريد الاستماع إلى نتيجة التجميع للاطّلاع على تعديلات في الوقت الفعلي.
لا تتيح طلبات البحث الخاصة بالتجميع
يمكنك تنفيذ تجميع وقت الكتابة باستخدام معاملة من جهة العميل أو باستخدام دوال Cloud. توضح الأقسام التالية كيفية تنفيذ تجميعات وقت الكتابة.
الحل: تجميع وقت الكتابة باستخدام معاملة من جهة العميل
فكّر في تطبيق توصيات محلية يساعد المستخدمين في العثور على مطاعم رائعة. يسترد الاستعلام التالي جميع التقييمات لمطعم معين:
الويب
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 لتعديل المعلومات المجمّعة في كل مرة تتم فيها إضافة تقييم جديد إلى مطعم:
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 للتجميعات إلى تجنُّب بعض المشاكل المتعلقة بالمعاملات من جهة العميل، ولكنه ينطوي على مجموعة مختلفة من القيود:
- التكلفة - سيؤدي كل تقييم تتم إضافته إلى استدعاء دالة Cloud، ما قد يؤدي إلى زيادة التكاليف. لمزيد من المعلومات، اطّلِع على صفحة أسعار دوال Cloud.
- وقت الاستجابة: من خلال نقل تجميع البيانات إلى دالة في السحابة الإلكترونية، لن يتمكّن تطبيقك من الاطّلاع على البيانات المعدَّلة إلى أن تنتهي عملية تنفيذ دالة Cloud ويتم إشعار العميل بالبيانات الجديدة. قد يستغرق ذلك وقتًا أطول من تنفيذ المعاملة على الجهاز وفقًا لسرعة وظيفة السحابة الإلكترونية.
- معدلات الكتابة - قد لا يعمل هذا الحل مع التجميعات التي يتم تعديلها بشكل متكرر لأن مستندات Cloud Firestore لا يمكن تعديلها إلا مرة واحدة في الثانية كحد أقصى. بالإضافة إلى ذلك، إذا اطّلعت المعاملة على مستند تم تعديله خارج نطاق المعاملة، تُعيد المحاولة لعدد محدود من المرات ثم يتعذّر إتمامها. اطّلِع على العدّادات الموزَّعة للحصول على حل بديل لعمليات التجميع التي تحتاج إلى المزيد من التحديثات المتكرّرة.