Zapytania w Cloud Firestore umożliwiają znajdowanie dokumentów w dużych zbiorach. Aby uzyskać wgląd w właściwości całego zbioru, możesz agregować dane w zbiorze.
Dane możesz agregować w czasie odczytu lub w czasie zapisu:
Agregacje w czasie odczytu obliczają wynik w momencie wysłania żądania. Cloud Firestore obsługuje zapytania agregujące
count(),sum()iaverage()w czasie odczytu. Zapytania agregujące w czasie odczytu łatwiej dodać do aplikacji niż agregacje w czasie zapisu. Więcej informacji o zapytaniach agregujących znajdziesz w artykule Podsumowywanie danych za pomocą zapytań agregujących.Agregacje w czasie zapisu obliczają wynik za każdym razem, gdy aplikacja wykonuje odpowiednią operację zapisu. Agregacje w czasie zapisu są trudniejsze do wdrożenia, ale możesz ich używać zamiast agregacji w czasie odczytu z jednego z tych powodów:
- Chcesz nasłuchiwać wyniku agregacji w celu uzyskiwania aktualizacji w czasie rzeczywistym.
Zapytania agregujące
count(),sum()iaverage()nie obsługują aktualizacji w czasie rzeczywistym. - Chcesz przechowywać wynik agregacji w pamięci podręcznej po stronie klienta.
Zapytania agregujące
count(),sum()iaverage()nie obsługują buforowania. - Agregujesz dane z dziesiątek tysięcy dokumentów dla każdego użytkownika i bierzesz pod uwagę koszty. Przy mniejszej liczbie dokumentów agregacje w czasie odczytu są tańsze. W przypadku dużej liczby dokumentów w agregacjach agregacje w czasie zapisu mogą być tańsze.
- Chcesz nasłuchiwać wyniku agregacji w celu uzyskiwania aktualizacji w czasie rzeczywistym.
Zapytania agregujące
Agregację w czasie zapisu możesz wdrożyć za pomocą transakcji po stronie klienta lub za pomocą Cloud Functions. W kolejnych sekcjach opisujemy, jak wdrożyć agregacje w czasie zapisu.
Rozwiązanie: agregacja w czasie zapisu za pomocą transakcji po stronie klienta
Załóżmy, że masz lokalną aplikację z rekomendacjami, która pomaga użytkownikom znajdować dobre restauracje. To zapytanie pobiera wszystkie oceny danej restauracji:
Sieć
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();
Zamiast pobierać wszystkie oceny, a potem obliczać informacje zbiorcze, możemy przechowywać te informacje w samym dokumencie restauracji:
Sieć
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);
Aby zachować spójność tych agregacji, należy je aktualizować za każdym razem, gdy do podzbioru zostanie dodana nowa ocena. Jednym ze sposobów na zachowanie spójności jest wykonanie dodawania i aktualizacji w ramach jednej transakcji:
Sieć
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; } }); }
Dzięki transakcji dane zbiorcze są spójne z bazowym zbiorem. Więcej informacji o transakcjach w Cloud Firestore, znajdziesz w artykule Transakcje i zapisy zbiorcze.
Ograniczenia
Rozwiązanie pokazane powyżej demonstruje agregowanie danych za pomocą biblioteki klienta Cloud Firestore, ale musisz pamiętać o tych ograniczeniach:
- Bezpieczeństwo – transakcje po stronie klienta wymagają przyznania klientom uprawnień do aktualizowania danych zbiorczych w bazie danych. Chociaż możesz zmniejszyć ryzyko związane z tym podejściem, pisząc zaawansowane reguły bezpieczeństwa, w niektórych sytuacjach może to nie być odpowiednie.
- Obsługa offline – transakcje po stronie klienta nie powiodą się, gdy urządzenie użytkownika jest offline. Oznacza to, że musisz obsłużyć ten przypadek w aplikacji i ponowić próbę w odpowiednim momencie.
- Wydajność – jeśli transakcja zawiera wiele operacji odczytu, zapisu i aktualizacji, może wymagać wielu żądań do Cloud Firestore backendu. Na urządzeniu mobilnym może to zająć sporo czasu.
- Szybkość zapisu – to rozwiązanie może nie działać w przypadku często aktualizowanych agregacji, ponieważ dokumenty Cloud Firestore można aktualizować co najwyżej raz na sekundę. Jeśli transakcja odczytuje dokument, który został zmodyfikowany poza transakcją, ponawia próbę określoną liczbę razy a potem kończy się niepowodzeniem. W przypadku agregacji, które wymagają częstszych aktualizacji, odpowiednim obejściem są liczniki rozproszone.
Rozwiązanie: agregacja w czasie zapisu za pomocą Cloud Functions
Jeśli transakcje po stronie klienta nie są odpowiednie dla Twojej aplikacji, możesz użyć Cloud Functions, aby aktualizować informacje zbiorcze za każdym razem, gdy do restauracji zostanie dodana nowa ocena:
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 }); }); });
To rozwiązanie przenosi pracę z klienta do funkcji hostowanej, co oznacza, że aplikacja mobilna może dodawać oceny bez czekania na zakończenie transakcji. Kod wykonywany w Cloud Functions nie jest ograniczony przez reguły bezpieczeństwa, co oznacza, że nie musisz już przyznawać klientom dostępu do zapisu danych zbiorczych.
Ograniczenia
Używanie Cloud Functions do agregacji pozwala uniknąć niektórych problemów z transakcjami po stronie klienta, ale wiąże się z innymi ograniczeniami:
- Koszt – każda dodana ocena spowoduje wywołanie Cloud Functions, co może zwiększyć koszty. Więcej informacji znajdziesz na stronie z cennikiem Cloud Functions .
- Opóźnienie – przeniesienie pracy związanej z agregacją do Cloud Functions spowoduje, że Twoja aplikacja nie będzie widzieć zaktualizowanych danych, dopóki Cloud Functions nie zakończy wykonywania i klient nie zostanie powiadomiony o nowych danych. W zależności od szybkości Cloud Functions może to potrwać dłużej niż wykonanie transakcji lokalnie.
- Szybkość zapisu – to rozwiązanie może nie działać w przypadku często aktualizowanych agregacji, ponieważ dokumenty Cloud Firestore można aktualizować co najwyżej raz na sekundę. Jeśli transakcja odczytuje dokument, który został zmodyfikowany poza transakcją, ponawia próbę określoną liczbę razy a potem kończy się niepowodzeniem. W przypadku agregacji, które wymagają częstszych aktualizacji, odpowiednim obejściem są liczniki rozproszone.