שאילתות ב-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
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
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
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 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 Functions לא כפוף לכללי אבטחה, ולכן אתם לא צריכים לתת ללקוחות גישת כתיבה לנתונים הנצברים.
מגבלות
שימוש בפונקציה של Cloud Functions לצבירות נתונים מונע חלק מהבעיות שקשורות לעסקאות בצד הלקוח, אבל יש לו מגבלות אחרות:
- עלות – כל דירוג שנוסף יגרום להפעלה של פונקציה של Cloud Functions, מה שעשוי להגדיל את העלויות. למידע נוסף, ראו את דף התמחור של Cloud Functions.
- זמן אחזור – כשמעבירים את עבודת הצבירה לפונקציה של Cloud Functions, האפליקציה לא תראה נתונים מעודכנים עד שהפונקציה של Cloud Functions תסיים לפעול והלקוח יקבל הודעה על הנתונים החדשים. בהתאם למהירות של הפונקציה ב-Cloud Functions, יכול להיות שהפעולה תימשך יותר זמן מאשר ביצוע הטרנזקציה באופן מקומי.
- קצבי כתיבה – יכול להיות שהפתרון הזה לא יעבוד עם צבירות שמתעדכנות לעיתים קרובות, כי אפשר לעדכן מסמכים ב-Cloud Firestore רק פעם אחת בשנייה לכל היותר. בנוסף, אם טרנזקציה קוראת מסמך ששונה מחוץ לטרנזקציה, היא מנסה שוב מספר סופי של פעמים ואז נכשלת. במאמר בנושא מונים מבוזרים מפורט פתרון עקיף רלוונטי לצבירות שצריך לעדכן בתדירות גבוהה יותר.