Aggregazioni al momento della scrittura

Le query in Cloud Firestore consentono di trovare documenti in raccolte di grandi dimensioni. Per ottenere informazioni sulle proprietà della raccolta nel suo complesso, puoi aggregare i dati in una raccolta.

Puoi aggregare i dati in fase di lettura o di scrittura:

  • Le aggregazioni in fase di lettura calcolano un risultato al momento della richiesta. Cloud Firestore supporta le query di aggregazione count(), sum() e average() in fase di lettura. Le query di aggregazione in fase di lettura sono più facili da aggiungere all'app rispetto alle aggregazioni in fase di scrittura. Per saperne di più sulle query di aggregazione, consulta Riassumere i dati con le query di aggregazione.

  • Le aggregazioni in fase di scrittura calcolano un risultato ogni volta che l'app esegue un'operazione di scrittura pertinente. Le aggregazioni in fase di scrittura richiedono più lavoro per l'implementazione, ma potresti utilizzarle al posto delle aggregazioni in fase di lettura per uno dei seguenti motivi:

    • Vuoi rimanere in ascolto del risultato dell'aggregazione per gli aggiornamenti in tempo reale. Le query di aggregazione count(), sum() e average() non supportano gli aggiornamenti in tempo reale.
    • Vuoi archiviare il risultato dell'aggregazione in una cache lato client. Le query di aggregazione count(), sum() e average() non supportano la memorizzazione nella cache.
    • Stai aggregando i dati di decine di migliaia di documenti per ogni utente e stai valutando i costi. Con un numero inferiore di documenti, le aggregazioni in fase di lettura costano meno. Per un numero elevato di documenti in un'aggregazione, le aggregazioni in fase di scrittura potrebbero costare meno.

Puoi implementare un'aggregazione in fase di scrittura utilizzando una transazione lato client o con Cloud Functions. Le sezioni seguenti descrivono come implementare le aggregazioni in fase di scrittura.

Soluzione: aggregazione in fase di scrittura con una transazione lato client

Considera un'app di consigli locali che aiuta gli utenti a trovare ottimi ristoranti. La query seguente recupera tutte le valutazioni per un determinato ristorante:

Web

db.collection("restaurants")
  .doc("arinell-pizza")
  .collection("ratings")
  .get();

Swift

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
do {
  let snapshot = try await db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .getDocuments()
  print(snapshot)
} catch {
  print(error)
}

Objective-C

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
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();

Anziché recuperare tutte le valutazioni e poi calcolare le informazioni aggregate, possiamo archiviare queste informazioni nel documento del ristorante stesso:

Web

var arinellDoc = {
  name: 'Arinell Pizza',
  avgRating: 4.65,
  numRatings: 683
};

Swift

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
struct Restaurant {

  let name: String
  let avgRating: Float
  let numRatings: Int

}

let arinell = Restaurant(name: "Arinell Pizza", avgRating: 4.65, numRatings: 683)

Objective-C

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
@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);

Per mantenere la coerenza di queste aggregazioni, è necessario aggiornarle ogni volta che viene aggiunta una nuova valutazione alla sotto-raccolta. Un modo per ottenere la coerenza è eseguire l'aggiunta e l'aggiornamento in un'unica transazione:

Web

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

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
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

Nota: questo prodotto non è disponibile su watchOS e sui target App Clip.
- (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;
        }
    });
}

L'utilizzo di una transazione mantiene la coerenza dei dati aggregati con la raccolta sottostante. Per saperne di più sulle transazioni in Cloud Firestore, consulta Transazioni e scritture batch.

Limitazioni

La soluzione mostrata sopra illustra l'aggregazione dei dati utilizzando la Cloud Firestore libreria client, ma devi tenere presente le seguenti limitazioni:

  • Sicurezza : le transazioni lato client richiedono la concessione ai client dell'autorizzazione ad aggiornare i dati aggregati nel database. Sebbene sia possibile ridurre i rischi di questo approccio scrivendo regole di sicurezza avanzate, questa soluzione potrebbe non essere appropriata in tutte le situazioni.
  • Supporto offline : le transazioni lato client non vanno a buon fine quando il dispositivo dell'utente è offline, il che significa che devi gestire questo caso nella tua app e riprovare al momento opportuno.
  • Prestazioni : se la transazione contiene più operazioni di lettura, scrittura e aggiornamento, potrebbe richiedere più richieste al Cloud Firestore backend. Su un dispositivo mobile, questa operazione potrebbe richiedere molto tempo.
  • Frequenza di scrittura : questa soluzione potrebbe non funzionare per le aggregazioni aggiornate di frequente perché i documenti di Cloud Firestore possono essere aggiornati al massimo una volta al secondo. Inoltre, se una transazione legge un documento modificato al di fuori della transazione, viene eseguito un numero finito di tentativi e poi non va a buon fine. Consulta i contatori distribuiti per una soluzione alternativa pertinente per le aggregazioni che richiedono aggiornamenti più frequenti.

Soluzione: aggregazione in fase di scrittura con Cloud Functions

Se le transazioni lato client non sono adatte alla tua applicazione, puoi utilizzare una funzione Cloud per aggiornare le informazioni aggregate ogni volta che viene aggiunta una nuova valutazione a un ristorante:

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
        });
      });
    });

Questa soluzione delega il lavoro dal client a una funzione ospitata, il che significa che la tua app mobile può aggiungere valutazioni senza attendere il completamento di una transazione. Il codice eseguito in una funzione Cloud non è vincolato dalle regole di sicurezza, il che significa che non devi più concedere ai client l'accesso in scrittura ai dati aggregati.

Limitazioni

L'utilizzo di una funzione Cloud per le aggregazioni evita alcuni dei problemi relativi alle transazioni lato client, ma presenta una serie di limitazioni diverse:

  • Costo : ogni valutazione aggiunta causerà una chiamata di funzione Cloud, che potrebbe aumentare i costi. Per saperne di più, consulta la pagina dei prezzi di Cloud Functions .
  • Latenza : delegando il lavoro di aggregazione a una funzione Cloud, la tua app non vedrà i dati aggiornati finché la funzione Cloud non avrà terminato l'esecuzione e il client non avrà ricevuto una notifica dei nuovi dati. A seconda della velocità della funzione Cloud, questa operazione potrebbe richiedere più tempo rispetto all'esecuzione della transazione in locale.
  • Frequenza di scrittura : questa soluzione potrebbe non funzionare per le aggregazioni aggiornate di frequente perché i documenti di Cloud Firestore possono essere aggiornati al massimo una volta al secondo. Inoltre, se una transazione legge un documento modificato al di fuori della transazione, viene eseguito un numero finito di tentativi e poi non va a buon fine. Consulta i contatori distribuiti per una soluzione alternativa pertinente per le aggregazioni che richiedono aggiornamenti più frequenti.