क्लाउड फायरस्टोर डेटा बंडल

क्लाउड फायरस्टोर डेटा बंडल आपके द्वारा क्लाउड फायरस्टोर दस्तावेज़ और क्वेरी स्नैपशॉट से निर्मित स्थिर डेटा फ़ाइलें हैं, और आपके द्वारा सीडीएन, होस्टिंग सेवा या अन्य समाधान पर प्रकाशित की जाती हैं। डेटा बंडल में वे दस्तावेज़ शामिल होते हैं जो आप अपने क्लाइंट ऐप्स को प्रदान करना चाहते हैं और उन प्रश्नों के बारे में मेटाडेटा जो उन्हें उत्पन्न करते हैं। आप नेटवर्क पर या स्थानीय स्टोरेज से बंडल डाउनलोड करने के लिए क्लाइंट एसडीके का उपयोग करते हैं, जिसके बाद आप बंडल डेटा को क्लाउड फायरस्टोर स्थानीय कैश में लोड करते हैं। एक बार बंडल लोड हो जाने पर, क्लाइंट ऐप स्थानीय कैश या बैकएंड से दस्तावेज़ों को क्वेरी कर सकता है।

डेटा बंडलों के साथ, आपके ऐप्स सामान्य प्रश्नों के परिणाम जल्दी लोड कर सकते हैं, क्योंकि दस्तावेज़ क्लाउड फायरस्टोर बैकएंड पर कॉल की आवश्यकता के बिना स्टार्ट-अप पर उपलब्ध हैं। यदि परिणाम स्थानीय कैश से लोड किए जाते हैं, तो आपको कम पहुंच लागत का भी लाभ मिलता है। उन्हीं प्रारंभिक 100 दस्तावेज़ों को क्वेरी करने के लिए दस लाख ऐप इंस्टेंस के लिए भुगतान करने के बजाय, आप केवल उन 100 दस्तावेज़ों को बंडल करने के लिए आवश्यक प्रश्नों के लिए भुगतान करते हैं।

क्लाउड फायरस्टोर डेटा बंडल अन्य फायरबेस बैकएंड उत्पादों के साथ अच्छी तरह से काम करने के लिए बनाए गए हैं। एक एकीकृत समाधान पर एक नज़र डालें जिसमें क्लाउड फ़ंक्शंस द्वारा बंडल बनाए जाते हैं और फ़ायरबेस होस्टिंग वाले उपयोगकर्ताओं को परोसे जाते हैं।

अपने ऐप के साथ बंडल का उपयोग करने में तीन चरण शामिल हैं:

  1. एडमिन एसडीके के साथ बंडल बनाना
  2. बंडल को स्थानीय भंडारण से या सीडीएन से प्रस्तुत करना
  3. क्लाइंट में बंडल लोड हो रहा है

डेटा बंडल क्या है?

डेटा बंडल एक स्थिर बाइनरी फ़ाइल है जो आपके द्वारा एक या अधिक दस्तावेज़ और/या क्वेरी स्नैपशॉट को पैकेज करने के लिए बनाई गई है और जिससे आप नामित क्वेरी निकाल सकते हैं। जैसा कि हम नीचे चर्चा करते हैं, सर्वर-साइड एसडीके आपको बंडल बनाने देते हैं और क्लाइंट एसडीके आपको स्थानीय कैश में बंडल लोड करने के तरीके प्रदान करते हैं।

नामांकित क्वेरीज़ बंडलों की एक विशेष रूप से शक्तिशाली विशेषता हैं। नामित क्वेरीज़ Query ऑब्जेक्ट हैं जिन्हें आप एक बंडल से निकाल सकते हैं, फिर कैश से या बैकएंड से डेटा को क्वेरी करने के लिए तुरंत उपयोग कर सकते हैं, जैसा कि आप सामान्य रूप से अपने ऐप के किसी भी हिस्से में करते हैं जो क्लाउड फायरस्टोर से बात करता है।

सर्वर पर डेटा बंडल बनाना

Node.js या Java एडमिन 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 विधि को कॉल करता है, जो एक कार्य ट्रैकिंग ऑब्जेक्ट लौटाता है, जिसके पूरा होने पर आप एक वादे की स्थिति की निगरानी कर सकते हैं। सफल बंडल लोडिंग कार्य पूरा होने पर, बंडल सामग्री स्थानीय कैश में उपलब्ध होती है।

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
  // ...
}
तीव्र
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
// 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)
  }
}
उद्देश्य सी
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
// 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 मिनट से कम समय पहले बनाए गए बंडल से नामित क्वेरी लोड करते हैं, तो एक बार जब आप इसे कैश के बजाय बैकएंड से पढ़ने के लिए उपयोग करते हैं, तो आप केवल बैकएंड पर संग्रहीत चीज़ों से मिलान करने के लिए दस्तावेज़ों को अपडेट करने के लिए आवश्यक डेटाबेस रीड्स के लिए भुगतान करेंगे। ; यानी, आप केवल डेल्टा के लिए भुगतान करते हैं।

आगे क्या?