Cloud Firestore 資料組合是由您透過 Cloud Firestore 文件和查詢快照建立的靜態資料檔案,且由您在 CDN、代管服務或其他解決方案上發布。資料套件包含您要提供給用戶端應用程式的文件,以及產生這些文件的查詢相關中繼資料。您使用用戶端 SDK 透過網路或本機儲存空間下載套件,然後將套件資料載入 Cloud Firestore 本機快取。載入軟體包後,用戶端應用程式即可從本機快取或後端查詢文件。
有了資料套件,應用程式就能在啟動時更快載入常見查詢結果,不需要呼叫 Cloud Firestore 後端。如果結果是從本機快取載入,您也可以享有較低的存取成本。您只需為將這 100 份文件彙整在一起所需的查詢付費,而不需要為 100 萬個應用程式執行個體付費。
Cloud Firestore 資料組合適用於其他 Firebase 後端產品。請查看由 Cloud Functions 建構的套件,並透過 Firebase Hosting 提供給使用者的整合解決方案。
如要在應用程式中使用套件,請執行以下三個步驟:
- 使用 Admin SDK 建構套件
- 從本機儲存空間或 CDN 提供套件
- 在用戶端載入套件
什麼是資料套件?
資料組合是由您建構的靜態二進位檔案,可用於封裝一或多個文件和/或查詢快照,以及從中擷取已命名查詢。如以下討論,您可以使用伺服器端 SDK 建構套件和用戶端 SDK,藉此將套件載入本機快取。
命名查詢是套裝組合中特別強大的功能。已命名查詢是可從套件擷取的 Query
物件,然後立即用於從快取或後端查詢資料,就像在應用程式內與 Cloud Firestore 通訊的任何部分一樣。
在伺服器上建構資料組合
使用 Node.js 或 Java Admin SDK 時,您可以完全控制套件中包含的內容,以及如何放送這些內容。
Node.js
var bundleId = "latest-stories"; var bundle = firestore.bundle(bundleId); var docSnapshot = await firestore.doc('stories/stories').get(); var querySnapshot = await firestore.collection('stories').get(); // Build the bundle // Note how querySnapshot is named "latest-stories-query" var bundleBuffer = bundle.add(docSnapshot); // Add a document .add('latest-stories-query', querySnapshot) // Add a named query. .build()
Java
Firestore db = FirestoreClient.getFirestore(app); // Query the 50 latest stories QuerySnapshot latestStories = db.collection("stories") .orderBy("timestamp", Direction.DESCENDING) .limit(50) .get() .get(); // Build the bundle from the query results FirestoreBundle bundle = db.bundleBuilder("latest-stories") .add("latest-stories-query", latestStories) .build();
Python
from google.cloud import firestore from google.cloud.firestore_bundle import FirestoreBundle db = firestore.Client() bundle = FirestoreBundle("latest-stories") doc_snapshot = db.collection("stories").document("news-item").get() query = db.collection("stories")._query() # Build the bundle # Note how `query` is named "latest-stories-query" bundle_buffer: str = bundle.add_document(doc_snapshot).add_named_query( "latest-stories-query", query, ).build()
提供資料組合
您可以透過 CDN 或從 Cloud Storage 等位置下載套件至用戶端應用程式。
假設先前建立的套件已儲存至名為 bundle.txt
的檔案,並發布至伺服器。這個套件檔案如同您能透過網路提供的任何其他素材資源,如簡易的 Node.js Express 應用程式所示。
const fs = require('fs');
const server = require('http').createServer();
server.on('request', (req, res) => {
const src = fs.createReadStream('./bundle.txt');
src.pipe(res);
});
server.listen(8000);
在用戶端中載入資料套裝組合
您可以透過發出 HTTP 要求、呼叫儲存空間 API 或使用其他方法,從遠端伺服器擷取 Firestore 套件,以便在網路上擷取二進位檔案。
擷取完成後,應用程式會使用 Cloud Firestore 用戶端 SDK 呼叫 loadBundle
方法,該方法會傳回工作追蹤物件,您可以監控該物件的完成情形,就像監控 Promise 的狀態一樣。成功完成套件載入工作後,即可在本機快取中找到軟體包內容。
Web
import { loadBundle, namedQuery, getDocsFromCache } from "firebase/firestore"; async function fetchFromBundle() { // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache' // response header will be set to 'HIT' const resp = await fetch('/createBundle'); // Load the bundle contents into the Firestore SDK await loadBundle(db, resp.body); // Query the results from the cache const query = await namedQuery(db, 'latest-stories-query'); const storiesSnap = await getDocsFromCache(query); // Use the results // ... }
Web
// If you are using module bundlers. import firebase from "firebase/app"; import "firebase/firestore"; import "firebase/firestore/bundle"; // This line enables bundle loading as a side effect. // ... async function fetchFromBundle() { // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache' // response header will be set to 'HIT' const resp = await fetch('/createBundle'); // Load the bundle contents into the Firestore SDK await db.loadBundle(resp.body); // Query the results from the cache // Note: omitting "source: cache" will query the Firestore backend. const query = await db.namedQuery('latest-stories-query'); const storiesSnap = await query.get({ source: 'cache' }); // Use the results // ... }
Swift
// Utility function for errors when loading bundles. func bundleLoadError(reason: String) -> NSError { return NSError(domain: "FIRSampleErrorDomain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: reason]) } func fetchRemoteBundle(for firestore: Firestore, from url: URL) async throws -> LoadBundleTaskProgress { guard let inputStream = InputStream(url: url) else { let error = self.bundleLoadError(reason: "Unable to create stream from the given url: \(url)") throw error } return try await firestore.loadBundle(inputStream) } // Fetches a specific named query from the provided bundle. func loadQuery(named queryName: String, fromRemoteBundle bundleURL: URL, with store: Firestore) async throws -> Query { let _ = try await fetchRemoteBundle(for: store, from: bundleURL) if let query = await store.getQuery(named: queryName) { return query } else { throw bundleLoadError(reason: "Could not find query named \(queryName)") } } // Load a query and fetch its results from a bundle. func runStoriesQuery() async { let queryName = "latest-stories-query" let firestore = Firestore.firestore() let remoteBundle = URL(string: "https://example.com/createBundle")! do { let query = try await loadQuery(named: queryName, fromRemoteBundle: remoteBundle, with: firestore) let snapshot = try await query.getDocuments() print(snapshot) // handle query results } catch { print(error) } }
Objective-C
// Utility function for errors when loading bundles. - (NSError *)bundleLoadErrorWithReason:(NSString *)reason { return [NSError errorWithDomain:@"FIRSampleErrorDomain" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey: reason}]; } // Loads a remote bundle from the provided url. - (void)fetchRemoteBundleForFirestore:(FIRFirestore *)firestore fromURL:(NSURL *)url completion:(void (^)(FIRLoadBundleTaskProgress *_Nullable, NSError *_Nullable))completion { NSInputStream *inputStream = [NSInputStream inputStreamWithURL:url]; if (inputStream == nil) { // Unable to create input stream. NSError *error = [self bundleLoadErrorWithReason: [NSString stringWithFormat:@"Unable to create stream from the given url: %@", url]]; completion(nil, error); return; } [firestore loadBundleStream:inputStream completion:^(FIRLoadBundleTaskProgress * _Nullable progress, NSError * _Nullable error) { if (progress == nil) { completion(nil, error); return; } if (progress.state == FIRLoadBundleTaskStateSuccess) { completion(progress, nil); } else { NSError *concreteError = [self bundleLoadErrorWithReason: [NSString stringWithFormat: @"Expected bundle load to be completed, but got %ld instead", (long)progress.state]]; completion(nil, concreteError); } completion(nil, nil); }]; } // Loads a bundled query. - (void)loadQueryNamed:(NSString *)queryName fromRemoteBundleURL:(NSURL *)url withFirestore:(FIRFirestore *)firestore completion:(void (^)(FIRQuery *_Nullable, NSError *_Nullable))completion { [self fetchRemoteBundleForFirestore:firestore fromURL:url completion:^(FIRLoadBundleTaskProgress *progress, NSError *error) { if (error != nil) { completion(nil, error); return; } [firestore getQueryNamed:queryName completion:^(FIRQuery *query) { if (query == nil) { NSString *errorReason = [NSString stringWithFormat:@"Could not find query named %@", queryName]; NSError *error = [self bundleLoadErrorWithReason:errorReason]; completion(nil, error); return; } completion(query, nil); }]; }]; } - (void)runStoriesQuery { NSString *queryName = @"latest-stories-query"; FIRFirestore *firestore = [FIRFirestore firestore]; NSURL *bundleURL = [NSURL URLWithString:@"https://example.com/createBundle"]; [self loadQueryNamed:queryName fromRemoteBundleURL:bundleURL withFirestore:firestore completion:^(FIRQuery *query, NSError *error) { // Handle query results }]; }
Kotlin+KTX
@Throws(IOException::class) fun getBundleStream(urlString: String?): InputStream { val url = URL(urlString) val connection = url.openConnection() as HttpURLConnection return connection.inputStream } @Throws(IOException::class) fun fetchFromBundle() { val bundleStream = getBundleStream("https://example.com/createBundle") val loadTask = db.loadBundle(bundleStream) // Chain the following tasks // 1) Load the bundle // 2) Get the named query from the local cache // 3) Execute a get() on the named query loadTask.continueWithTask<Query> { task -> // Close the stream bundleStream.close() // Calling .result propagates errors val progress = task.getResult(Exception::class.java) // Get the named query from the bundle cache db.getNamedQuery("latest-stories-query") }.continueWithTask { task -> val query = task.getResult(Exception::class.java)!! // get() the query results from the cache query.get(Source.CACHE) }.addOnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Bundle loading failed", task.exception) return@addOnCompleteListener } // Get the QuerySnapshot from the bundle val storiesSnap = task.result // Use the results // ... } }
Java
public InputStream getBundleStream(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); return connection.getInputStream(); } public void fetchBundleFrom() throws IOException { final InputStream bundleStream = getBundleStream("https://example.com/createBundle"); LoadBundleTask loadTask = db.loadBundle(bundleStream); // Chain the following tasks // 1) Load the bundle // 2) Get the named query from the local cache // 3) Execute a get() on the named query loadTask.continueWithTask(new Continuation<LoadBundleTaskProgress, Task<Query>>() { @Override public Task<Query> then(@NonNull Task<LoadBundleTaskProgress> task) throws Exception { // Close the stream bundleStream.close(); // Calling getResult() propagates errors LoadBundleTaskProgress progress = task.getResult(Exception.class); // Get the named query from the bundle cache return db.getNamedQuery("latest-stories-query"); } }).continueWithTask(new Continuation<Query, Task<QuerySnapshot>>() { @Override public Task<QuerySnapshot> then(@NonNull Task<Query> task) throws Exception { Query query = task.getResult(Exception.class); // get() the query results from the cache return query.get(Source.CACHE); } }).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (!task.isSuccessful()) { Log.w(TAG, "Bundle loading failed", task.getException()); return; } // Get the QuerySnapshot from the bundle QuerySnapshot storiesSnap = task.getResult(); // Use the results // ... } }); }
Dart
// Get a bundle from a server final url = Uri.https('example.com', '/create-bundle'); final response = await http.get(url); String body = response.body; final buffer = Uint8List.fromList(body.codeUnits); // Load a bundle from a buffer LoadBundleTask task = FirebaseFirestore.instance.loadBundle(buffer); await task.stream.toList(); // Use the cached named query final results = await FirebaseFirestore.instance.namedQueryGet( "latest-stories-query", options: const GetOptions( source: Source.cache, ), );
C++
db->LoadBundle("bundle_name", [](const LoadBundleTaskProgress& progress) { switch(progress.state()) { case LoadBundleTaskProgress::State::kError: { // The bundle load has errored. Handle the error in the returned future. return; } case LoadBundleTaskProgress::State::kInProgress: { std::cout << "Bytes loaded from bundle: " << progress.bytes_loaded() << std::endl; break; } case LoadBundleTaskProgress::State::kSuccess: { std::cout << "Bundle load succeeeded" << std::endl; break; } } }).OnCompletion([db](const Future<LoadBundleTaskProgress>& future) { if (future.error() != Error::kErrorOk) { // Handle error... return; } const std::string& query_name = "latest_stories_query"; db->NamedQuery(query_name).OnCompletion([](const Future<Query>& query_future){ if (query_future.error() != Error::kErrorOk) { // Handle error... return; } const Query* query = query_future.result(); query->Get().OnCompletion([](const Future<QuerySnapshot> &){ // ... }); }); });
請注意,如果您是從在 30 分鐘內建構的套件載入具名查詢,使用從後端讀取 (而非快取) 時,僅須支付更新文件所需的資料庫讀取費用,以符合後端儲存的內容;也就是說,您只需支付差異的費用。
後續步驟
請參閱用戶端 (Apple、Android、網頁) 和伺服器端 (Node.js) 的資料套裝組合 API 參考說明文件。
如果您還沒有,請參閱Cloud Functions 和 Firebase Hosting 解決方案,瞭解如何建構及提供套件。