Mantenha tudo organizado com as coleções Salve e categorize o conteúdo com base nas suas preferências.

Consultas de agregação

Com as consultas avançadas no Firestore, é possível encontrar rapidamente documentos em grandes coleções. Agregue toda a coleção para saber mais sobre as propriedades dela como um todo.

O Firestore é compatível com consultas de agregação count() no servidor. Porém, para casos de uso específicos, é possível usar transações do lado do cliente ou o Cloud Functions para manter informações agregadas sobre os dados.

Antes de continuar, leia sobre consultas e o modelo de dados do Firestore.

Solução: transações do lado do cliente

Pense em um app de recomendação de locais que ajude os usuários a encontrar bons restaurantes. A seguinte consulta recupera todas as avaliações de um determinado restaurante:

Web

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

Swift

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .getDocuments() { (querySnapshot, err) in

        // ...

}

Objective-C

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
FIRQuery *query = [[[self.db collectionWithPath:@"restaurants"]
    documentWithPath:@"arinell-pizza"] collectionWithPath:@"ratings"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                    NSError * _Nullable error) {
  // ...
}];

Kotlin+KTX
Android

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

Java
Android

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

Em vez de buscar todas as avaliações e depois computar as informações agregadas, é possível armazenar esses dados no próprio documento do restaurante:

Web

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

Swift

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
struct Restaurant {

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

    init(name: String, avgRating: Float, numRatings: Int) {
        self.name = name
        self.avgRating = avgRating
        self.numRatings = numRatings
    }

}

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

Objective-C

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
@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
Android

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
Android

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

Para manter essas agregações consistentes, é necessário fazer atualizações sempre que uma nova avaliação é adicionada à subcoleção. Uma forma de conseguir consistência é realizar a inclusão e a atualização em uma transação única:

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

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
func addRatingTransaction(restaurantRef: DocumentReference, rating: Float) {
    let ratingRef: DocumentReference = restaurantRef.collection("ratings").document()

    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
    }) { (object, err) in
        // ...
    }
}

Objective-C

Observação: esse produto não está disponível para destinos watchOS e de clipes de apps.
- (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
Android

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
Android

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

O uso de uma transação mantém os dados agregados consistentes com a coleção. Para saber mais sobre transações no Firestore, consulte Transações e gravações em lote.

Limitações

Na solução apresentada acima, os dados foram agregados usando a biblioteca de cliente do Firestore, mas esteja ciente das limitações a seguir:

  • Segurança: para as transações do lado do cliente, é necessário que ele tenha permissão para atualizar os dados agregados no seu banco de dados. É possível reduzir os riscos dessa abordagem com a criação de regras de segurança avançadas, mas isso pode não ser apropriado em algumas situações.
  • Suporte off-line: as transações do lado do cliente apresentarão falha quando o dispositivo do usuário estiver off-line. Sendo assim, é necessário lidar com esse caso no seu app e tentar novamente no momento oportuno.
  • Desempenho: caso sua transação tenha várias operações de leitura, gravação e atualização, ela poderá exigir diversas solicitações para o back-end do Firestore. Em um dispositivo móvel, isso pode ser demorado.
  • Taxas de gravação: essa solução pode não funcionar para agregações atualizadas com frequência, já que os documentos do Cloud Firestore podem ser atualizados no máximo uma vez por segundo. Além disso, se uma transação ler um documento que foi modificado fora dela, o processo será repetido um número finito de vezes e, em seguida, falhará. Confira os contadores distribuídos para uma solução alternativa de agregações que precisam ser atualizadas com mais frequência.

Solução: Cloud Functions

Se as transações do lado do cliente não forem adequadas ao seu aplicativo, use uma função do Cloud para atualizar as informações agregadas sempre que uma nova avaliação for adicionada a um restaurante:

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

O trabalho do lado do cliente é descarregado por essa solução em uma função hospedada, o que significa que seu aplicativo para dispositivos móveis pode adicionar avaliações sem esperar pela conclusão de uma transação. O código executado em uma Cloud Function não está vinculado por regras de segurança e, dessa forma, não é mais necessário oferecer aos clientes acesso de escrita aos dados agregados.

Limitações

É possível evitar alguns problemas nas transações do lado do cliente ao usar uma função do Cloud para agregações, mas essa abordagem apresenta um conjunto diferente de limitações:

  • Custo: cada avaliação adicionada faz uma função do Cloud ser invocada, o que vai aumentar os custos. Para mais informações, consulte a página de preços do Cloud Functions.
  • Latência: com o descarregamento do trabalho de agregação em uma função do Cloud, não é possível ver dados atualizados até que ela tenha terminado a execução e o cliente tenha sido notificado sobre os novos dados. Dependendo da velocidade da função do Cloud, isso pode levar mais tempo do que executar a transação localmente.
  • Taxas de gravação: essa solução pode não funcionar para agregações atualizadas com frequência, já que os documentos do Cloud Firestore podem ser atualizados no máximo uma vez por segundo. Além disso, se uma transação ler um documento que foi modificado fora dela, o processo será repetido um número finito de vezes e, em seguida, falhará. Confira os contadores distribuídos para uma solução alternativa de agregações que precisam ser atualizadas com mais frequência.