寫入時間匯總

您可以透過 Cloud Firestore 查詢尋找文件 大型集合中。為了深入瞭解 可以匯總集合的資料。

您可以在讀取時或寫入時匯總資料:

  • 讀取時間匯總功能會在要求時計算結果。 Cloud Firestore 支援 count()sum()average() 匯總查詢。讀取時間匯總查詢更簡單 而不是寫入時間匯總如要進一步瞭解 匯總查詢,請參閱使用匯總查詢匯總資料

  • 寫入時間匯總會在應用程式每次執行時計算結果 相關的寫入作業寫入時間匯總較有實作上的工作 但針對其中一個 。

    • 您想監聽匯總結果來即時更新。 不支援 count()sum()average() 匯總查詢 即時更新。
    • 您想將匯總結果儲存在用戶端快取中。 不支援 count()sum()average() 匯總查詢 快取功能。
    • 正在匯總各個資料集的數萬份文件的資料 並考量成本少量文件的讀取時間 匯總費用較低如果是匯總作業中的大量文件 寫入時間匯總的費用可能較低。

您可以使用用戶端或用戶端執行寫入時間匯總 交易或 Cloud Functions以下各節��明如何執行 寫入時間匯總

解決方案:透過用戶端交易進行寫入時間匯總

假設有一款當地推薦應用程式,可協助使用者找到美味的餐廳。 以下查詢會擷取特定餐廳的所有評分:

網路

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

Swift

注意:這項產品不適用於 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
};

Swift

注意:這項產品不適用於 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 });
        });
    });
}

Swift

注意:這項產品不適用於 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 用戶端程式庫,但請注意下列事項 限制:

  • 安全性 - 用戶端交易需要授予用戶端權限 更新資料庫中的匯總資料。雖然您可以減少 這種做法的風險 不一定適合各種情境
  • 離線支援:使用者裝置會導致用戶端交易失敗 處於離線狀態,也就是說,請在應用程式中處理這種情況,然後再試一次 在適當的時機放送
  • 「效能」:如果您的交易包含多次讀取、寫入與 可能需要對 Pod 執行多個要求 Cloud Firestore 後端以行動裝置來說,這 相當可觀
  • 寫入費率 - 這個解決方案可能無法經常更新 Cloud Firestore 文件最多只能更新 每秒搜尋一次此外,如果交易讀取的文件 而在交易外部修改後,它會重試無限次 結果卻失敗查看分散式計數器 ,瞭解需要更頻繁更新的匯總解決方案。

解決方案:使用 Cloud Functions 進行寫入時間匯總

如果用戶端交易不適合您的應用程式,您可以使用 Cloud 函式,用於更新匯總資訊 每當餐廳新增評分時:

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 函式中執行的程式碼不受安全性規則約束。 因此,您不再需要授予用戶端寫入匯總權限 資料。

限制

使用 Cloud 函式匯總可以避免發生 用戶端交易,但還是有不同的限制:

  • 費用:您新增的每個等級都會導致發出 Cloud 函式叫用。 可能會導致費用增加詳情請參閱 Cloud Functions 定價頁面
  • 延遲時間 - 將匯總工作卸載至 Cloud 函式後, Cloud 函式完成前,應用程式不會看到更新的資料 並已通知用戶端有新資料。視乎 Cloud 函式的速度,這可能需要 本機交易
  • 寫入費率 - 這個解決方案可能無法經常更新 Cloud Firestore 文件最多只能更新 每秒搜尋一次此外,如果交易讀取的文件 而在交易外部修改後,它會重試無限次 結果卻失敗查看分散式計數器 ,瞭解需要更頻繁更新的匯總解決方案。