Com as consultas avançadas no Firestore, é possível encontrar rapidamente documentos em grandes coleções. Para saber mais sobre as propriedades da coleção como um todo, será necessário agregar toda a coleção.
O Firestore não é compatível com consultas de agregação nativas. No entanto, é possível usar transações do lado do cliente ou o Cloud Functions para manter com facilidade 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
db.collection("restaurants")
.document("arinell-pizza")
.collection("ratings")
.getDocuments() { (querySnapshot, err) in
// ...
}
Objective-C
FIRQuery *query = [[[self.db collectionWithPath:@"restaurants"]
documentWithPath:@"arinell-pizza"] collectionWithPath:@"ratings"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
NSError * _Nullable error) {
// ...
}];
Java
Android
db.collection("restaurants") .document("arinell-pizza") .collection("ratings") .get();
Kotlin+KTX
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 essas informações no próprio documento do restaurante:
Web
var arinellDoc = {
name: 'Arinell Pizza',
avgRating: 4.65,
numRatings: 683
};
Swift
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
@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
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);
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)
Para manter essas agregações consistentes, é necessário atualizá-las 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
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
- (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) {
// ...
}];
}
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(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; } }); }
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 } }
O uso de uma transação mantém os dados agregados consistentes com a coleção subjacente. 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. Reduzir os riscos dessa abordagem com a escrita de regras de segurança avançadas pode não ser apropriado em todas as 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.
Solução: Cloud Functions
Se as transações do lado do cliente não forem adequadas ao seu aplicativo, use uma Cloud Function 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 com transações do lado do cliente com o uso de uma Cloud Function, mas essa abordagem apresenta um conjunto diferente de limitações:
- Custo: cada avaliação adicionada causa uma invocação da Cloud Function, o que pode 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 Cloud Function, 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 do Cloud Function, isso pode levar mais tempo do que executar a transação localmente.