Zapytania w Cloud Firestore umożliwiają znajdowanie dokumentów w dużych kolekcjach. Aby uzyskać wgląd w usługi w kolekcji jako całości, możesz agregować dane w kolekcji.
Dane możesz agregować w momencie odczytu lub zapisu:
Agregacje w czasie odczytu obliczają wynik w momencie wysłania żądania. Cloud Firestore obsługuje w czasie odczytu zapytania o agregację
count()
,sum()
iaverage()
. Zapytania zbiorcze wykonywane w czasie odczytu łatwiej jest dodać do aplikacji niż zapytania zbiorcze wykonywane 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 momencie zapisu są trudniejsze do wdrożenia, ale możesz ich używać zamiast agregacji w momencie odczytu z jednego z tych powodów:
- Chcesz słuchać wyniku agregacji, aby otrzymywać aktualizacje w czasie rzeczywistym.
Zapytania o agregację
count()
,sum()
iaverage()
nie obsługują aktualizacji w czasie rzeczywistym. - Chcesz zapisać wynik agregacji w pamięci podręcznej po stronie klienta.
Zapytania o agregację
count()
,sum()
iaverage()
nie obsługują buforowania. - Zbierasz dane z dziesiątek tysięcy dokumentów dla każdego użytkownika i bierzesz pod uwagę koszty. Przy mniejszej liczbie dokumentów agregacje czasu czytania są tańsze. W przypadku dużej liczby dokumentów w agregacjach agregacje w czasie zapisu mogą być tańsze.
- Chcesz słuchać wyniku agregacji, aby otrzymywać aktualizacje w czasie rzeczywistym.
Zapytania o agregację
Agregację w momencie zapisu możesz wdrożyć za pomocą transakcji po stronie klienta lub za pomocą Cloud Functions. W sekcjach poniżej znajdziesz opis implementacji agregacji w momencie zapisu.
Rozwiązanie: agregacja w momencie zapisu z użyciem transakcji po stronie klienta
Rozważ aplikację z lokalnymi rekomendacjami, która pomaga użytkownikom znajdować świetne 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 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 osiągnięcie spójności jest wykonanie operacji dodawania i aktualizowania 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; } }); }
Użycie transakcji zapewnia spójność danych zbiorczych z bazową kolekcją. Więcej informacji o transakcjach w Cloud Firestore znajdziesz w artykule Transakcje i zapisywanie zbiorcze.
Ograniczenia
Rozwiązanie pokazane powyżej demonstruje agregowanie danych za pomocą biblioteki klientaCloud Firestore, ale musisz pamiętać o tych ograniczeniach:
- Bezpieczeństwo – transakcje po stronie klienta wymagają przyznania klientom uprawnień do aktualizowania danych zbiorczych w Twojej bazie danych. Ryzyko związane z tym podejściem możesz zmniejszyć, pisząc zaawansowane reguły zabezpieczeń, ale nie zawsze będzie to odpowiednie rozwiązanie.
- 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 swojej aplikacji i ponowić próbę w odpowiednim czasie.
- Wydajność – jeśli transakcja zawiera wiele operacji odczytu, zapisu i aktualizacji, może wymagać wielu żądań do backendu Cloud Firestore. 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ć maksymalnie raz na sekundę. Jeśli transakcja odczytuje dokument, który został zmodyfikowany poza nią, ponawia próbę określoną liczbę razy, a potem kończy się niepowodzeniem. Więcej informacji o odpowiednim obejściu problemu w przypadku agregacji, które wymagają częstszych aktualizacji, znajdziesz w artykule o rozproszonych licznikach.
Rozwiązanie: agregacja w momencie zapisu za pomocą Cloud Functions
Jeśli transakcje po stronie klienta nie są odpowiednie dla Twojej aplikacji, możesz użyć funkcji Cloud, 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 na hostowaną funkcję, co oznacza, że aplikacja mobilna może dodawać oceny bez czekania na zakończenie transakcji. Kod wykonywany w Cloud Functions nie podlega regułom bezpieczeństwa, co oznacza, że nie musisz już przyznawać klientom dostępu do zapisu zagregowanych danych.
Ograniczenia
Używanie funkcji 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 funkcji w 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 funkcji w Cloud Functions spowoduje, że aplikacja nie będzie widzieć zaktualizowanych danych, dopóki funkcja w Cloud Functions nie zakończy działania, a klient nie zostanie powiadomiony o nowych danych. W zależności od szybkości działania funkcji w 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ć maksymalnie raz na sekundę. Jeśli transakcja odczytuje dokument, który został zmodyfikowany poza nią, ponawia próbę określoną liczbę razy, a potem kończy się niepowodzeniem. Więcej informacji o odpowiednim obejściu problemu w przypadku agregacji, które wymagają częstszych aktualizacji, znajdziesz w artykule o rozproszonych licznikach.