Cloud Firestore डेटा बंडल आपके द्वारा Cloud Firestore दस्तावेज़ और क्वेरी स्नैपशॉट से निर्मित और CDN, होस्टिंग सेवा या अन्य समाधान पर आपके द्वारा प्रकाशित स्थिर डेटा फ़ाइलें हैं। डेटा बंडल में वे दस्तावेज़ शामिल होते हैं, जिन्हें आप अपने क्लाइंट ऐप्स को प्रदान करना चाहते हैं और उन क्वेरीज़ के बारे में मेटाडेटा, जिन्होंने उन्हें उत्पन्न किया है। आप नेटवर्क पर या स्थानीय संग्रहण से बंडल डाउनलोड करने के लिए क्लाइंट SDK का उपयोग करते हैं, जिसके बाद आप बंडल डेटा को Cloud Firestore स्थानीय कैश में लोड करते हैं। एक बार बंडल लोड हो जाने के बाद, क्लाइंट ऐप स्थानीय कैश या बैकएंड से दस्तावेज़ों को क्वेरी कर सकता है।
डेटा बंडलों के साथ, आपके ऐप्स सामान्य प्रश्नों के परिणामों को जल्द ही लोड कर सकते हैं, क्योंकि दस्तावेज़ क्लाउड फायरस्टोर बैकएंड पर कॉल की आवश्यकता के बिना स्टार्ट-अप पर उपलब्ध हैं। यदि परिणाम स्थानीय कैश से लोड किए जाते हैं, तो आपको एक्सेस की कम लागत का भी लाभ मिलता है। समान प्रारंभिक 100 दस्तावेज़ों को क्वेरी करने के लिए एक लाख ऐप इंस्टेंस के भुगतान के बजाय, आप केवल उन 100 दस्तावेज़ों को बंडल करने के लिए आवश्यक क्वेरी के लिए भुगतान करते हैं।
क्लाउड फायरस्टोर डेटा बंडल अन्य फायरबेस बैकएंड उत्पादों के साथ अच्छी तरह से काम करने के लिए बनाए गए हैं। एक एकीकृत समाधान पर एक नज़र डालें जिसमें क्लाउड फ़ंक्शंस द्वारा बंडल बनाए जाते हैं और फायरबेस होस्टिंग वाले उपयोगकर्ताओं को सेवा प्रदान की जाती है।
अपने ऐप के साथ बंडल का उपयोग करने में तीन चरण शामिल हैं:
- एडमिन SDK के साथ बंडल बनाना
- बंडल को स्थानीय स्टोरेज या सीडीएन से सर्व करना
- क्लाइंट में बंडल लोड हो रहा है
डेटा बंडल क्या है?
एक डेटा बंडल एक स्थिर बाइनरी फ़ाइल है जिसे आपने एक या अधिक दस्तावेज़ और/या क्वेरी स्नैपशॉट पैकेज करने के लिए बनाया है और जिससे आप नामित क्वेरी निकाल सकते हैं। जैसा कि हम नीचे चर्चा करते हैं, सर्वर-साइड एसडीके आपको बंडल बनाने देते हैं और क्लाइंट एसडीके आपको स्थानीय कैश में बंडल लोड करने के तरीके प्रदान करते हैं।
नामांकित प्रश्न बंडलों की एक विशेष रूप से शक्तिशाली विशेषता है। नामित क्वेरी वे Query
ऑब्जेक्ट हैं जिन्हें आप बंडल से निकाल सकते हैं, फिर कैश या बैकएंड से डेटा क्वेरी करने के लिए तुरंत उपयोग करें, जैसा कि आप अपने ऐप के किसी भी हिस्से में सामान्य रूप से करते हैं जो क्लाउड फायरस्टोर से बात करता है।
सर्वर पर डेटा बंडल बनाना
Node.js या Java Admin SDK का उपयोग करने से आपको बंडल में क्या शामिल करना है और उन्हें कैसे प्रस्तुत करना है, इस पर पूरा नियंत्रण मिलता है।
नोड.जेएस
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()
जावा
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();
अजगर
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()
डेटा बंडलों की सेवा
आप सीडीएन से या उदाहरण के लिए, क्लाउड स्टोरेज से डाउनलोड करके अपने क्लाइंट ऐप्स को बंडल प्रदान कर सकते हैं।
मान लें कि पिछले अनुभाग में बनाए गए बंडल को bundle.txt
नामक फ़ाइल में सहेजा गया है और सर्वर पर पोस्ट किया गया है। यह बंडल फ़ाइल किसी अन्य संपत्ति की तरह है जिसे आप वेब पर सर्व कर सकते हैं, जैसा कि एक साधारण Node.js एक्सप्रेस ऐप के लिए यहां दिखाया गया है।
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 अनुरोध करके, स्टोरेज एपीआई को कॉल करके या नेटवर्क पर बाइनरी फ़ाइलों को लाने के लिए किसी अन्य तकनीक का उपयोग करके।
प्राप्त करने के बाद, क्लाउड फायरस्टार क्लाइंट एसडीके का उपयोग करके, आपका ऐप loadBundle
विधि को कॉल करता है, जो एक कार्य ट्रैकिंग ऑब्जेक्ट देता है, जिसके पूरा होने पर आप किसी वादे की स्थिति की निगरानी के रूप में बहुत अधिक निगरानी कर सकते हैं। सफल बंडल लोडिंग कार्य पूरा होने पर, स्थानीय कैश में बंडल सामग्री उपलब्ध होती है।
वेब
// 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 // ... }
तीव्र
// Utility function for errors when loading bundles. func bundleLoadError(reason: String) -> NSError { return NSError(domain: "FIRSampleErrorDomain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: reason]) } // Loads a remote bundle from the provided url. func fetchRemoteBundle(for firestore: Firestore, from url: URL, completion: @escaping ((Result<LoadBundleTaskProgress, Error>) -> ())) { guard let inputStream = InputStream(url: url) else { let error = self.bundleLoadError(reason: "Unable to create stream from the given url: \(url)") completion(.failure(error)) return } // The return value of this function is ignored, but can be used for more granular // bundle load observation. let _ = firestore.loadBundle(inputStream) { (progress, error) in switch (progress, error) { case (.some(let value), .none): if value.state == .success { completion(.success(value)) } else { let concreteError = self.bundleLoadError( reason: "Expected bundle load to be completed, but got \(value.state) instead" ) completion(.failure(concreteError)) } case (.none, .some(let concreteError)): completion(.failure(concreteError)) case (.none, .none): let concreteError = self.bundleLoadError(reason: "Operation failed, but returned no error.") completion(.failure(concreteError)) case (.some(let value), .some(let concreteError)): let concreteError = self.bundleLoadError( reason: "Operation returned error \(concreteError) with nonnull progress: \(value)" ) completion(.failure(concreteError)) } } } // Fetches a specific named query from the provided bundle. func loadQuery(named queryName: String, fromRemoteBundle bundleURL: URL, with store: Firestore, completion: @escaping ((Result<Query, Error>) -> ())) { fetchRemoteBundle(for: store, from: bundleURL) { (result) in switch result { case .success: store.getQuery(named: queryName) { query in if let query = query { completion(.success(query)) } else { completion( .failure( self.bundleLoadError(reason: "Could not find query named \(queryName)") ) ) } } case .failure(let error): completion(.failure(error)) } } } // Load a query and fetch its results from a bundle. func runStoriesQuery() { let queryName = "latest-stories-query" let firestore = Firestore.firestore() let remoteBundle = URL(string: "https://example.com/createBundle")! loadQuery(named: queryName, fromRemoteBundle: remoteBundle, with: firestore) { (result) in switch result { case .failure(let error): print(error) case .success(let query): query.getDocuments { (snapshot, error) in // handle query results } } } }
उद्देश्य सी
// 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 // ... } }); }
सी ++
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 संदर्भ दस्तावेज़ देखें।
यदि आपने पहले से नहीं किया है, तो बंडल बनाने और प्रस्तुत करने के लिए क्लाउड फ़ंक्शंस और फायरबेस होस्टिंग समाधान पर एक नज़र डालें।