寫入時聚合

Cloud Firestore 中的查詢可讓您在大型集合中尋找文件。若要深入了解整個集合的屬性,您可以聚合集合上的資料。

您可以在讀取時或寫入時聚合資料:

  • 讀取時聚合在請求時計算結果。 Cloud Firestore 支援讀取時的count()sum()average()聚合查詢。讀取時聚合查詢比寫入時聚合更容易添加到您的應用程式中。有關聚合查詢的更多信息,請參閱使用聚合查詢匯總資料

  • 寫入時聚合會在應用程式每次執行相關寫入操作時計算結果。寫入時聚合的實作需要更多工作,但出於以下原因之一,您可能會使用它們而不是讀取時聚合:

    • 您想要監聽聚合結果以進行即時更新。 count()sum()average()聚合查詢不支援即時更新。
    • 您希望將聚合結果儲存在客戶端快取中。 count()sum()average()聚合查詢不支援快取。
    • 您正在為每個使用者聚合數以萬計的文件中的資料並考慮成本。文件數量越少,讀取時聚合的成本就越低。對於聚合中的大量文檔,寫入時聚合的成本可能會更低。

您可以使用客戶端事務或 Cloud Functions 來實現寫入時聚合。以下部分說明如何實現寫入時聚合。

解決方案:使用客戶端事務進行寫入時聚合

考慮一個可以幫助用戶找到很棒的餐廳的當地推薦應用程式。以下查詢檢索給定餐廳的所有評級:

網路

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

迅速

注意:此產品不適用於 watchOS 和 App Clip 目標。
do {
  let snapshot = try await db.collection("restaurants")
    .document("arinell-pizza")
    .collection("ratings")
    .getDocuments()
  print(snapshot)
} catch {
  print(error)
}

Objective-C

注意:此產品不適用於 watchOS 和 App Clip 目標。
FIRQuery *query = [[[self.db collectionWithPath:@"restaurants"]
    documentWithPath:@"arinell-pizza"] collectionWithPath:@"ratings"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                    NSError * _Nullable error) {
  // ...
}];

Kotlin+KTX

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

Java

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

我們可以將此資訊儲存在餐廳文件本身上,而不是獲取所有評級然後計算聚合資訊:

網路

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

迅速

注意:此產品不適用於 watchOS 和 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

注意:此產品不適用於 watchOS 和 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+KTX

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

為了保持這些聚合的一致性,每次將新評級新增至子集合時都必須更新它們。實現一致性的一種方法是在單一事務中執行新增和更新:

網路

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

迅速

注意:此產品不適用於 watchOS 和 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

注意:此產品不適用於 watchOS 和 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+KTX

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

使用事務可以使聚合資料與底層集合保持一致。若要詳細了解 Cloud Firestore 中的事務,請參閱事務和批次寫入

限制

上面顯示的解決方案示範了使用 Cloud Firestore 用戶端庫聚合數據,但您應該注意以下限制:

  • 安全性- 客戶端事務需要授予客戶端更新資料庫中聚合資料的權限。雖然您可以透過撰寫進階安全規則來降低此方法的風險,但這可能不適合所有情況。
  • 離線支援- 當使用者的裝置離線時,客戶端交易將會失敗,這表示您需要在應用程式中處理這種情況,並在適當的時間重試。
  • 效能- 如果您的事務包含多個讀取、寫入和更新操作,則可能需要向 Cloud Firestore 後端發出多個請求。在行動裝置上,這可能需要大量時間。
  • 寫入速率- 此解決方案可能不適用於頻繁更新的聚合,因為 Cloud Firestore 文件每秒最多只能更新一次。此外,如果事務讀取在事務外部修改的文檔,它會重試有限次數,然後失敗。查看分散式計數器,了解需要更頻繁更新的聚合的相關解決方法。

解決方案:使用 Cloud Functions 進行寫入時聚合

如果客戶端交易不適合您的應用程序,您可以使用雲端函數在每次向餐廳添加新評級時更新聚合資訊:

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

該解決方案將工作從客戶端卸載到託管功能,這意味著您的行動應用程式可以添加評級,而無需等待交易完成。在雲端函數中執行的程式碼不受安全規則的約束,這表示您不再需要向客戶端授予對聚合資料的寫入存取權限。

限制

使用雲端函數進行聚合可以避免客戶端事務的一些問題,但會帶來一組不同的限制:

  • 成本- 添加的每個評級都會導致一次 Cloud Function 調用,這可能會增加您的成本。有關更多信息,請參閱 Cloud Functions定價頁面
  • 延遲- 透過將聚合工作卸載到雲端函數,您的應用程式將不會看到更新的數據,直到雲端函數完成執行並且客戶端已收到新數據的通知。根據雲端功能的速度,這可能比在本地執行事務需要更長的時間。
  • 寫入速率- 此解決方案可能不適用於頻繁更新的聚合,因為 Cloud Firestore 文件每秒最多只能更新一次。此外,如果事務讀取在事務外部修改的文檔,它會重試有限次數,然後失敗。查看分散式計數器,了解需要更頻繁更新的聚合的相關解決方法。