Las consultas avanzadas de Firestore te permiten encontrar con rapidez documentos en colecciones de gran tamaño. Si quieres obtener información sobre las propiedades de una colección como un todo, necesitarás la agregación en una colección.
Firestore no admite consultas de agregación nativas. Sin embargo, puedes usar transacciones del cliente o Cloud Functions para mantener fácilmente la información agregada sobre tus datos.
Antes de continuar, asegúrate de que leíste la información sobre las consultas y el modelo de datos de Firestore.
Solución: Transacciones del cliente
Piensa en una app de recomendaciones locales que ayuda a los usuarios a encontrar excelentes restaurantes. La siguiente consulta recupera todas las calificaciones de un restaurante específico:
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()
En lugar de recuperar todas las calificaciones y luego calcular la información agregada, podemos almacenar esta información en el propio documento del 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 mantener la coherencia de estas agregaciones, se deben actualizar cada vez que se agrega una nueva calificación a la subcolección. Una forma de lograr la coherencia es ejecutar las operaciones de agregar y actualizar en la misma transacción:
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 } }
Cuando se usa una transacción, se mantiene la coherencia entre los datos agregados y los datos subyacentes. Para obtener más información sobre las transacciones en Firestore, consulta Transacciones y escrituras en lotes.
Limitaciones
En la solución anterior se demuestra la agregación de datos mediante la biblioteca cliente de Firestore, pero debes tener en cuenta estas limitaciones:
- Seguridad: Las transacciones del cliente requieren que los clientes tengan permiso para actualizar los datos totales en su base de datos. Si bien es posible reducir el riesgo de este enfoque mediante reglas de seguridad avanzadas, esa solución podría no resultar adecuada para todas las situaciones.
- Soporte sin conexión: Las transacciones del cliente fallarán cuando el dispositivo del usuario esté sin conexión, lo que implica que debes manejar este caso en tu app y volver a intentarlo en el momento oportuno.
- Rendimiento: Si tu transacción contiene varias operaciones de lectura, escritura y actualización, es posible que debas enviar solicitudes al backend de Firestore. En un dispositivo móvil, esto podría tardar bastante tiempo.
Solución: Cloud Functions
Si las transacciones del lado del cliente no son adecuadas para tu aplicación, puedes usar una función de Cloud Functions para actualizar la información agregada cada vez que se suma una nueva calificación a un 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
});
});
});
Con esta solución, una función alojada realiza el trabajo en lugar del cliente, por lo que tu app para dispositivos móviles puede agregar calificaciones sin esperar a que se complete una transacción. El código ejecutado en una función de Cloud Functions no está sujeto a las reglas de seguridad, lo que significa que ya no es necesario que los clientes tengan acceso de escritura a los datos agregados.
Limitaciones
Usar una función de Cloud Functions para las agregaciones evita algunos problemas en las transacciones de cliente, pero acarrea un conjunto diferente de limitaciones:
- Costo: Cada calificación que se agrega genera una llamada a la función de Cloud Functions, lo cual puede aumentar tus costos. Para obtener más información, consulta la página de precios de Cloud Functions.
- Latencia: Dado que el trabajo de agregación se deriva a una función de Cloud Functions, tu app no verá los datos actualizados hasta que la función haya terminado de ejecutarse y el cliente haya recibido una notificación de los datos nuevos. Según la velocidad de tu función de Cloud Functions, esto podría tardar más que ejecutar la transacción de forma local.