Zapytania w Cloud Firestore pozwalają znajdować dokumenty w dużych kolekcjach. Aby uzyskać wgląd we właściwości kolekcji jako całości, można agregować dane dotyczące całej kolekcji.
Dane można agregować w czasie odczytu lub zapisu:
Agregacje czasu odczytu obliczają wynik w momencie żądania. Cloud Firestore obsługuje zapytania agregujące
count()
,sum()
iaverage()
w czasie odczytu. Zapytania agregujące w czasie odczytu są łatwiejsze do dodania do aplikacji niż agregacje w czasie zapisu. Więcej informacji na temat zapytań agregujących zawiera sekcja Podsumowanie danych za pomocą zapytań agregujących .Agregacje czasu zapisu obliczają wynik za każdym razem, gdy aplikacja wykonuje odpowiednią operację zapisu. Agregacje w czasie zapisu wymagają więcej pracy, ale można ich używać zamiast agregacji w czasie odczytu z jednego z następujących powodów:
- Chcesz odsłuchać wynik agregacji w celu uzyskania 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 ze swoich użytkowników i rozważasz koszty. Przy mniejszej liczbie dokumentów agregacja czasu odczytu kosztuje mniej. W przypadku dużej liczby dokumentów w agregacji agregacje czasu zapisu mogą kosztować mniej.
- Chcesz odsłuchać wynik agregacji w celu uzyskania aktualizacji w czasie rzeczywistym. Zapytania agregujące
Agregację czasu zapisu możesz zaimplementować przy użyciu transakcji po stronie klienta lub Cloud Functions. W poniższych sekcjach opisano sposób implementowania agregacji czasu zapisu.
Rozwiązanie: Agregacja czasu zapisu z transakcją po stronie klienta
Rozważ aplikację z lokalnymi rekomendacjami, która pomoże użytkownikom znaleźć świetne restauracje. Poniższe zapytanie pobiera wszystkie oceny dla danej restauracji:
Sieć
db.collection("restaurants") .doc("arinell-pizza") .collection("ratings") .get();
Szybki
do { let snapshot = try await db.collection("restaurants") .document("arinell-pizza") .collection("ratings") .getDocuments() print(snapshot) } catch { print(error) }
Cel 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();
Zamiast pobierać wszystkie oceny, a następnie obliczać zbiorcze informacje, możemy przechowywać te informacje w samym dokumencie restauracji:
Sieć
var arinellDoc = { name: 'Arinell Pizza', avgRating: 4.65, numRatings: 683 };
Szybki
struct Restaurant { let name: String let avgRating: Float let numRatings: Int } let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683)
Cel 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);
Aby zachować spójność tych agregacji, należy je aktualizować za każdym razem, gdy do podzbioru dodawana jest nowa ocena. Jednym ze sposobów osiągnięcia spójności jest wykonanie dodawania i aktualizacji w 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 }); }); }); }
Szybki
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 { // ... } }
Cel 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; } }); }
Korzystanie z transakcji zapewnia spójność danych zbiorczych z bazową kolekcją. Aby przeczytać więcej o transakcjach w Cloud Firestore, zobacz Transakcje i zapisy wsadowe .
Ograniczenia
Rozwiązanie pokazane powyżej demonstruje agregację danych przy użyciu biblioteki klienta Cloud Firestore, ale należy pamiętać o następujących ograniczeniach:
- Bezpieczeństwo — transakcje po stronie klienta wymagają udzielenia klientom pozwolenia na aktualizację zbiorczych danych w bazie danych. Chociaż ryzyko związane z tym podejściem można zmniejszyć, pisząc zaawansowane reguły bezpieczeństwa, może to nie być odpowiednie we wszystkich sytuacjach.
- Wsparcie offline — transakcje po stronie klienta nie powiodą się, gdy urządzenie użytkownika będzie w trybie offline, co oznacza, że musisz obsłużyć tę sprawę w swojej aplikacji i spróbować ponownie w odpowiednim momencie.
- Wydajność — jeśli transakcja obejmuje wiele operacji odczytu, zapisu i aktualizacji, może wymagać wielu żądań do zaplecza Cloud Firestore. Na urządzeniu mobilnym może to zająć dużo czasu.
- Szybkość zapisu — to rozwiązanie może nie działać w przypadku często aktualizowanych agregacji, ponieważ dokumenty Cloud Firestore można aktualizować najwyżej raz na sekundę. Ponadto, jeśli transakcja odczytuje dokument, który został zmodyfikowany poza transakcją, podejmuje próbę ponawiania skończonej liczby razy , a następnie kończy się niepowodzeniem. Sprawdź liczniki rozproszone , aby znaleźć odpowiednie obejście dla agregacji, które wymagają częstszych aktualizacji.
Rozwiązanie: Agregacja czasu zapisu za pomocą Cloud Functions
Jeśli transakcje po stronie klienta nie są odpowiednie dla Twojej aplikacji, możesz użyć funkcji chmury , aby zaktualizować 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ę klienta na hostowaną funkcję, co oznacza, że Twoja aplikacja mobilna może dodawać oceny bez czekania na zakończenie transakcji. Kod wykonywany w Funkcji Cloud nie jest objęty regułami bezpieczeństwa, co oznacza, że nie musisz już zapewniać klientom dostępu do zapisu zagregowanych danych.
Ograniczenia
Korzystanie z funkcji chmury do agregacji pozwala uniknąć niektórych problemów związanych z transakcjami po stronie klienta, ale wiąże się z innym zestawem ograniczeń:
- Koszt — każda dodana ocena spowoduje wywołanie funkcji Cloud Function, co może zwiększyć koszty. Więcej informacji znajdziesz na stronie z cennikiem Cloud Functions.
- Opóźnienie — przenosząc pracę agregacyjną do Funkcji Cloud, Twoja aplikacja nie będzie widzieć zaktualizowanych danych do czasu zakończenia wykonywania Funkcji Cloud i powiadomienia klienta o nowych danych. W zależności od szybkości Twojej Funkcji Cloud może to zająć więcej czasu niż lokalna realizacja transakcji.
- Szybkość zapisu — to rozwiązanie może nie działać w przypadku często aktualizowanych agregacji, ponieważ dokumenty Cloud Firestore można aktualizować najwyżej raz na sekundę. Ponadto, jeśli transakcja odczytuje dokument, który został zmodyfikowany poza transakcją, podejmuje próbę ponawiania skończonej liczby razy , a następnie kończy się niepowodzeniem. Sprawdź liczniki rozproszone , aby znaleźć odpowiednie obejście dla agregacji, które wymagają częstszych aktualizacji.