Gói dữ liệu Cloud Firestore là các tệp dữ liệu tĩnh do bạn tạo từ tài liệu Cloud Firestore và ảnh chụp nhanh truy vấn, đồng thời được bạn xuất bản trên CDN, dịch vụ lưu trữ hoặc giải pháp khác. Gói dữ liệu bao gồm cả tài liệu bạn muốn cung cấp cho ứng dụng khách và siêu dữ liệu về các truy vấn đã tạo ra chúng. Bạn sử dụng SDK khách để tải xuống các gói qua mạng hoặc từ bộ nhớ cục bộ, sau đó bạn tải dữ liệu gói vào bộ nhớ đệm cục bộ của Cloud Firestore. Sau khi tải một gói, ứng dụng khách có thể truy vấn tài liệu từ bộ đệm cục bộ hoặc chương trình phụ trợ.
Với gói dữ liệu, ứng dụng của bạn có thể tải kết quả của các truy vấn phổ biến sớm hơn vì tài liệu có sẵn khi khởi động mà không cần gọi tới phần phụ trợ của Cloud Firestore. Nếu kết quả được tải từ bộ đệm cục bộ, bạn cũng được hưởng lợi từ việc giảm chi phí truy cập. Thay vì trả tiền cho một triệu phiên bản ứng dụng để truy vấn cùng 100 tài liệu ban đầu, bạn chỉ trả tiền cho những truy vấn cần thiết để gộp 100 tài liệu đó.
Gói dữ liệu Cloud Firestore được xây dựng để hoạt động tốt với các sản phẩm phụ trợ Firebase khác. Hãy xem giải pháp tích hợp trong đó các gói được Cloud Functions xây dựng và phân phát cho người dùng bằng Firebase Hosting.
Sử dụng gói với ứng dụng của bạn bao gồm ba bước:
- Xây dựng gói bằng SDK quản trị
- Cung cấp gói từ bộ nhớ cục bộ hoặc từ CDN
- Đang tải các gói trong máy khách
Gói dữ liệu là gì?
Gói dữ liệu là một tệp nhị phân tĩnh do bạn xây dựng để đóng gói một hoặc nhiều ảnh chụp nhanh tài liệu và/hoặc truy vấn và từ đó bạn có thể trích xuất các truy vấn được đặt tên . Như chúng ta thảo luận bên dưới, SDK phía máy chủ cho phép bạn xây dựng các gói và SDK khách cung cấp các phương thức để cho phép bạn tải các gói vào bộ nhớ đệm cục bộ.
Truy vấn được đặt tên là một tính năng đặc biệt mạnh mẽ của gói. Truy vấn được đặt tên là các đối tượng Query
mà bạn có thể trích xuất từ một gói, sau đó sử dụng ngay để truy vấn dữ liệu từ bộ đệm hoặc từ chương trình phụ trợ, như bạn thường làm trong bất kỳ phần nào trong ứng dụng của mình có giao tiếp với Cloud Firestore.
Xây dựng gói dữ liệu trên máy chủ
Việc sử dụng Node.js hoặc SDK quản trị Java sẽ mang lại cho bạn toàn quyền kiểm soát những gì cần đưa vào gói và cách phân phát chúng.
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()
Cung cấp gói dữ liệu
Bạn có thể phân phát các gói tới ứng dụng khách của mình từ CDN hoặc bằng cách tải chúng xuống, chẳng hạn như từ Cloud Storage.
Giả sử gói được tạo ở phần trước đã được lưu vào tệp có tên bundle.txt
và được đăng trên máy chủ. Tệp gói này giống như bất kỳ nội dung nào khác mà bạn có thể phân phát qua web, như được hiển thị ở đây cho ứng dụng Node.js Express đơn giản.
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);
Đang tải gói dữ liệu trong máy khách
Bạn tải các gói Firestore bằng cách tìm nạp chúng từ máy chủ từ xa, cho dù bằng cách thực hiện yêu cầu HTTP, gọi API lưu trữ hay sử dụng bất kỳ kỹ thuật nào khác để tìm nạp tệp nhị phân trên mạng.
Sau khi được tìm nạp, bằng cách sử dụng SDK máy khách Cloud Firestore, ứng dụng của bạn sẽ gọi phương thức loadBundle
, phương thức này trả về một đối tượng theo dõi tác vụ, việc hoàn thành đối tượng này bạn có thể theo dõi nhiều như bạn theo dõi trạng thái của Lời hứa. Khi hoàn thành nhiệm vụ tải gói thành công, nội dung gói sẽ có sẵn trong bộ đệm cục bộ.
Web modular API
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 namespaced API
// 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 // ... }
Nhanh
// 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) } }
Mục tiêu-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 // ... } }); }
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> &){ // ... }); }); });
Lưu ý rằng nếu bạn tải một truy vấn có tên từ một gói được tạo trước đó chưa đầy 30 phút, thì khi bạn sử dụng truy vấn đó để đọc từ phần phụ trợ thay vì bộ nhớ đệm, bạn sẽ chỉ trả tiền cho những lần đọc cơ sở dữ liệu cần thiết để cập nhật tài liệu cho khớp với những gì được lưu trữ trên phần phụ trợ ; nghĩa là bạn chỉ trả tiền cho vùng đồng bằng.
Tiếp theo là gì?
Tham khảo tài liệu tham khảo API gói dữ liệu cho phía máy khách ( Apple , Android , web ) và phía máy chủ ( Node.js ).
Nếu bạn chưa làm vậy, hãy xem giải pháp Cloud Functions và Firebase Hosting để xây dựng và phân phát các gói .