डेटा को ऑफ़लाइन ऐक्सेस करना

Cloud Firestore, ऑफ़लाइन डेटा को सेव रखने की सुविधा के साथ काम करता है. यह सुविधा, Cloud Firestore के उस डेटा की कॉपी को कैश मेमोरी में सेव करती है जिसका इस्तेमाल आपका ऐप्लिकेशन कर रहा है. इससे, डिवाइस के ऑफ़लाइन होने पर भी आपका ऐप्लिकेशन उस डेटा को ऐक्सेस कर सकता है. कैश मेमोरी में सेव किए गए डेटा को लिखा, पढ़ा, सुना, और उससे जुड़ी क्वेरी की जा सकती है. जब डिवाइस फिर से ऑनलाइन होता है, तो Cloud Firestore आपके ऐप्लिकेशन से किए गए किसी भी स्थानीय बदलाव को Cloud Firestore बैकएंड के साथ सिंक करता है.

ऑफ़लाइन पर्सिस्टेंस का इस्तेमाल करने के लिए, आपको उस कोड में कोई बदलाव करने की ज़रूरत नहीं है जिसका इस्तेमाल Cloud Firestore डेटा को ऐक्सेस करने के लिए किया जाता है. ऑफ़लाइन पर्सिस्टेंस की सुविधा चालू होने पर, Cloud Firestore क्लाइंट लाइब्रेरी, ऑनलाइन और ऑफ़लाइन डेटा ऐक्सेस को अपने-आप मैनेज करती है. साथ ही, डिवाइस के ऑनलाइन होने पर स्थानीय डेटा को सिंक करती है.

ऑफ़लाइन पर्सिस्टेंस कॉन्फ़िगर करना

Cloud Firestore को शुरू करने पर, ऑफ़लाइन पर्सिस्टेंस को चालू या बंद किया जा सकता है:

  • Android और Apple प्लैटफ़ॉर्म के लिए, ऑफ़लाइन पर्सिस्टेंस की सुविधा डिफ़ॉल्ट रूप से चालू रहती है. डेटा सेव होने की सुविधा बंद करने के लिए, PersistenceEnabled विकल्प को false पर सेट करें.
  • वेब के लिए, ऑफ़लाइन रहने की सुविधा डिफ़ॉल्ट रूप से बंद होती है. डेटा को सेव रखने की सुविधा चालू करने के लिए, enablePersistence तरीके को कॉल करें. Cloud Firestore का कैश मेमोरी, सेशन के बीच अपने-आप नहीं मिटता. इसलिए, अगर आपका वेब ऐप्लिकेशन संवेदनशील जानकारी मैनेज करता है, तो उपयोगकर्ता से यह पूछना न भूलें कि क्या वह किसी भरोसेमंद डिवाइस का इस्तेमाल कर रहा है. इसके बाद ही, पर्सिस्टेंस को चालू करें.
// Memory cache is the default if no config is specified.
initializeFirestore(app);

// This is the default behavior if no persistence is specified.
initializeFirestore(app, {localCache: memoryLocalCache()});

// Defaults to single-tab persistence if no tab manager is specified.
initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})});

// Same as `initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})})`,
// but more explicit about tab management.
initializeFirestore(app, 
  {localCache: 
    persistentLocalCache(/*settings*/{tabManager: persistentSingleTabManager()})
});

// Use multi-tab IndexedDb persistence.
initializeFirestore(app, 
  {localCache: 
    persistentLocalCache(/*settings*/{tabManager: persistentMultipleTabManager()})
  });
  
firebase.firestore().enablePersistence()
  .catch((err) => {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }
  });
// Subsequent queries will use persistence, if it was enabled successfully
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
let settings = FirestoreSettings()

// Use memory-only cache
settings.cacheSettings =
MemoryCacheSettings(garbageCollectorSettings: MemoryLRUGCSettings())

// Use persistent disk cache, with 100 MB cache size
settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber)

// Any additional options
// ...

// Enable offline data persistence
let db = Firestore.firestore()
db.settings = settings
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
FIRFirestoreSettings *settings = [[FIRFirestoreSettings alloc] init];

// Use memory-only cache
settings.cacheSettings = [[FIRMemoryCacheSettings alloc]
    initWithGarbageCollectorSettings:[[FIRMemoryLRUGCSettings alloc] init]];

// Use persistent disk cache (default behavior)
// This example uses 100 MB.
settings.cacheSettings = [[FIRPersistentCacheSettings alloc]
    initWithSizeBytes:@(100 * 1024 * 1024)];

// Any additional options
// ...

// Enable offline data persistence
FIRFirestore *db = [FIRFirestore firestore];
db.settings = settings;
val settings = firestoreSettings {
    // Use memory cache
    setLocalCacheSettings(memoryCacheSettings {})
    // Use persistent disk cache (default)
    setLocalCacheSettings(persistentCacheSettings {})
}
db.firestoreSettings = settings
FirebaseFirestoreSettings settings = 
new FirebaseFirestoreSettings.Builder(db.getFirestoreSettings())
    // Use memory-only cache
    .setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
    // Use persistent disk cache (default)
    .setLocalCacheSettings(PersistentCacheSettings.newBuilder()
                            .build())
    .build();
db.setFirestoreSettings(settings);
// Apple and Android
db.settings = const Settings(persistenceEnabled: true);

// Web
await db
    .enablePersistence(const PersistenceSettings(synchronizeTabs: true));

कैश मेमोरी का साइज़ कॉन्फ़िगर करना

डेटा सेव रखने की सुविधा चालू होने पर, Cloud Firestore ऑफ़लाइन ऐक्सेस के लिए, बैकएंड से मिले हर दस्तावेज़ को कैश मेमोरी में सेव करता है. Cloud Firestore, कैश मेमोरी के साइज़ के लिए डिफ़ॉल्ट थ्रेशोल्ड सेट करता है. डिफ़ॉल्ट स्टोरेज भर जाने के बाद, Cloud Firestore समय-समय पर पुराने और इस्तेमाल न किए गए दस्तावेज़ों को मिटाने की कोशिश करता है. कैश मेमोरी के साइज़ का थ्रेशोल्ड अलग से कॉन्फ़िगर किया जा सकता है या क्लीन-अप प्रोसेस को पूरी तरह से बंद किया जा सकता है:

import { initializeFirestore, CACHE_SIZE_UNLIMITED } from "firebase/firestore";

const firestoreDb = initializeFirestore(app, {
  cacheSizeBytes: CACHE_SIZE_UNLIMITED
});
firebase.firestore().settings({
    cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED
});
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "FirestoreCacheSizeUnlimited"
// to disable clean-up.
let settings = Firestore.firestore().settings
// Set cache size to 100 MB
settings.cacheSettings = PersistentCacheSettings(sizeBytes: 100 * 1024 * 1024 as NSNumber)
Firestore.firestore().settings = settings
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
// The default cache size threshold is 100 MB. Configure "cacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "kFIRFirestoreCacheSizeUnlimited"
// to disable clean-up.
FIRFirestoreSettings *settings = [FIRFirestore firestore].settings;
// Set cache size to 100 MB
settings.cacheSettings =
    [[FIRPersistentCacheSettings alloc] initWithSizeBytes:@(100 * 1024 * 1024)];
[FIRFirestore firestore].settings = settings;
  

// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED"
// to disable clean-up.
val settings = FirebaseFirestoreSettings.Builder()
        .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
        .build()
db.firestoreSettings = settings

// The default cache size threshold is 100 MB. Configure "setCacheSizeBytes"
// for a different threshold (minimum 1 MB) or set to "CACHE_SIZE_UNLIMITED"
// to disable clean-up.
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
        .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
        .build();
db.setFirestoreSettings(settings);
db.settings = const Settings(
  persistenceEnabled: true,
  cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
);

ऑफ़लाइन डेटा सुनना

अगर आपने डिवाइस के ऑफ़लाइन रहने पर भी डेटा सेव रखने की सुविधा चालू की है, तो डिवाइस के कैश मेमोरी में सेव किए गए डेटा में बदलाव होने पर, आपके दर्शकों को सुनने से जुड़े इवेंट मिलेंगे. आपके पास दस्तावेज़ों, कलेक्शन, और क्वेरी को सुनने का विकल्प होता है.

यह देखने के लिए कि आपको सर्वर से डेटा मिल रहा है या कैश मेमोरी से, अपने स्नैपशॉट इवेंट में SnapshotMetadata पर fromCache प्रॉपर्टी का इस्तेमाल करें. अगर fromCache true है, तो इसका मतलब है कि डेटा कैश मेमोरी से मिला है. हो सकता है कि यह डेटा पुराना हो या अधूरा हो. अगर fromCache की वैल्यू false है, तो इसका मतलब है कि डेटा पूरा है और सर्वर पर मौजूद नए अपडेट के हिसाब से अप-टू-डेट है.

डिफ़ॉल्ट रूप से, अगर SnapshotMetadata में सिर्फ़ बदलाव होता है, तो कोई इवेंट नहीं जनरेट होता. अगर fromCache वैल्यू का इस्तेमाल किया जाता है, तो listen हैंडलर को अटैच करते समय includeMetadataChanges listen विकल्प तय करें.

import { collection, onSnapshot, where, query } from "firebase/firestore"; 

const q = query(collection(db, "cities"), where("state", "==", "CA"));
onSnapshot(q, { includeMetadataChanges: true }, (snapshot) => {
    snapshot.docChanges().forEach((change) => {
        if (change.type === "added") {
            console.log("New city: ", change.doc.data());
        }

        const source = snapshot.metadata.fromCache ? "local cache" : "server";
        console.log("Data came from " + source);
    });
});
db.collection("cities").where("state", "==", "CA")
  .onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
      snapshot.docChanges().forEach((change) => {
          if (change.type === "added") {
              console.log("New city: ", change.doc.data());
          }

          var source = snapshot.metadata.fromCache ? "local cache" : "server";
          console.log("Data came from " + source);
      });
  });
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
// Listen to metadata updates to receive a server snapshot even if
// the data is the same as the cached data.
db.collection("cities").whereField("state", isEqualTo: "CA")
  .addSnapshotListener(includeMetadataChanges: true) { querySnapshot, error in
    guard let snapshot = querySnapshot else {
      print("Error retreiving snapshot: \(error!)")
      return
    }

    for diff in snapshot.documentChanges {
      if diff.type == .added {
        print("New city: \(diff.document.data())")
      }
    }

    let source = snapshot.metadata.isFromCache ? "local cache" : "server"
    print("Metadata: Data fetched from \(source)")
  }
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
// Listen to metadata updates to receive a server snapshot even if
// the data is the same as the cached data.
[[[db collectionWithPath:@"cities"] queryWhereField:@"state" isEqualTo:@"CA"]
    addSnapshotListenerWithIncludeMetadataChanges:YES
    listener:^(FIRQuerySnapshot *snapshot, NSError *error) {
      if (snapshot == nil) {
        NSLog(@"Error retreiving snapshot: %@", error);
        return;
      }
      for (FIRDocumentChange *diff in snapshot.documentChanges) {
        if (diff.type == FIRDocumentChangeTypeAdded) {
          NSLog(@"New city: %@", diff.document.data);
        }
      }

      NSString *source = snapshot.metadata.isFromCache ? @"local cache" : @"server";
      NSLog(@"Metadata: Data fetched from %@", source);
    }];
db.collection("cities").whereEqualTo("state", "CA")
    .addSnapshotListener(MetadataChanges.INCLUDE) { querySnapshot, e ->
        if (e != null) {
            Log.w(TAG, "Listen error", e)
            return@addSnapshotListener
        }

        for (change in querySnapshot!!.documentChanges) {
            if (change.type == DocumentChange.Type.ADDED) {
                Log.d(TAG, "New city: ${change.document.data}")
            }

            val source = if (querySnapshot.metadata.isFromCache) {
                "local cache"
            } else {
                "server"
            }
            Log.d(TAG, "Data fetched from $source")
        }
    }
db.collection("cities").whereEqualTo("state", "CA")
        .addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot querySnapshot,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w(TAG, "Listen error", e);
                    return;
                }

                for (DocumentChange change : querySnapshot.getDocumentChanges()) {
                    if (change.getType() == Type.ADDED) {
                        Log.d(TAG, "New city:" + change.getDocument().getData());
                    }

                    String source = querySnapshot.getMetadata().isFromCache() ?
                            "local cache" : "server";
                    Log.d(TAG, "Data fetched from " + source);
                }

            }
        });
db
    .collection("cities")
    .where("state", isEqualTo: "CA")
    .snapshots(includeMetadataChanges: true)
    .listen((querySnapshot) {
  for (var change in querySnapshot.docChanges) {
    if (change.type == DocumentChangeType.added) {
      final source =
          (querySnapshot.metadata.isFromCache) ? "local cache" : "server";

      print("Data fetched from $source}");
    }
  }
});

ऑफ़लाइन डेटा पाना

अगर डिवाइस ऑफ़लाइन होने पर आपको कोई दस्तावेज़ मिलता है, तो Cloud Firestore कैश मेमोरी से डेटा दिखाता है.

किसी कलेक्शन के लिए क्वेरी करने पर, अगर कैश मेमोरी में कोई दस्तावेज़ सेव नहीं है, तो कोई नतीजा नहीं मिलता. किसी खास दस्तावेज़ को फ़ेच करते समय, गड़बड़ी का मैसेज दिखता है.

ऑफ़लाइन डेटा की क्वेरी करना

क्वेरी करने की सुविधा, ऑफ़लाइन पर्सिस्टेंस के साथ काम करती है. क्वेरी के नतीजे, डायरेक्ट तौर पर पाने या सुनकर हासिल किए जा सकते हैं. इस बारे में, ऊपर दिए गए सेक्शन में बताया गया है. डिवाइस के ऑफ़लाइन होने पर भी, डिवाइस में सेव किए गए डेटा पर नई क्वेरी बनाई जा सकती हैं. हालांकि, शुरुआत में क्वेरी सिर्फ़ कैश मेमोरी में सेव किए गए दस्तावेज़ों के लिए ही चलेंगी.

ऑफ़लाइन क्वेरी इंडेक्स कॉन्फ़िगर करना

डिफ़ॉल्ट रूप से, Firestore SDK टूल, ऑफ़लाइन क्वेरी को लागू करते समय, किसी कलेक्शन के सभी दस्तावेज़ों को अपने लोकल कैश मेमोरी में स्कैन करता है. डिफ़ॉल्ट तौर पर, जब उपयोगकर्ता लंबे समय तक ऑफ़लाइन रहते हैं, तो ऑफ़लाइन क्वेरी की परफ़ॉर्मेंस पर असर पड़ सकता है.

पर्सिस्टेंट कैश की सुविधा चालू होने पर, SDK टूल को स्थानीय क्वेरी इंडेक्स अपने-आप बनाने की अनुमति देकर, ऑफ़लाइन क्वेरी की परफ़ॉर्मेंस को बेहतर बनाया जा सकता है.

अपने-आप इंडेक्स होने की सुविधा डिफ़ॉल्ट रूप से बंद होती है. आपका ऐप्लिकेशन हर बार शुरू होने पर, अपने-आप इंडेक्स होने की सुविधा चालू करेगा. नीचे दिए गए तरीके से यह कंट्रोल करें कि अपने-आप इंडेक्स होने की सुविधा चालू है या नहीं.

SwiftObjective-CKotlinJava
if let indexManager = Firestore.firestore().persistentCacheIndexManager {
  // Indexing is disabled by default
  indexManager.enableIndexAutoCreation()
} else {
  print("indexManager is nil")
}
    
PersistentCacheIndexManager *indexManager = [FIRFirestore firestore].persistentCacheIndexManager;
if (indexManager) {
  // Indexing is disabled by default
  [indexManager enableIndexAutoCreation];
}
    
// return type: PersistentCacheManager?

Firebase.firestore.persistentCacheIndexManager?.apply {
      // Indexing is disabled by default
      enableIndexAutoCreation()
    } ?: println("indexManager is null")
    
// return type: @Nullable PersistentCacheIndexManager
PersistentCacheIndexManager indexManager = FirebaseFirestore.getInstance().getPersistentCacheIndexManager();
if (indexManager != null) {
  // Indexing is disabled by default
  indexManager.enableIndexAutoCreation();
}

// If not check indexManager != null, IDE shows warning: Method invocation 'enableIndexAutoCreation' may produce 'NullPointerException' 
FirebaseFirestore.getInstance().getPersistentCacheIndexManager().enableIndexAutoCreation();
    

अपने-आप इंडेक्स होने की सुविधा चालू होने के बाद, SDK टूल यह आकलन करता है कि किन कलेक्शन में बड़ी संख्या में कैश मेमोरी में सेव दस्तावेज़ हैं. साथ ही, यह लोकल क्वेरी की परफ़ॉर्मेंस को ऑप्टिमाइज़ करता है.

एसडीके टूल, क्वेरी इंडेक्स मिटाने का तरीका उपलब्ध कराता है.

नेटवर्क ऐक्सेस की सुविधा को बंद और चालू करना

अपने Cloud Firestore क्लाइंट के लिए नेटवर्क ऐक्सेस बंद करने के लिए, यहां दिए गए तरीके का इस्तेमाल किया जा सकता है. नेटवर्क ऐक्सेस बंद होने पर, सभी स्नैपशॉट के लिसनर और दस्तावेज़ के अनुरोध, कैश मेमोरी से नतीजे पाते हैं. नेटवर्क ऐक्सेस फिर से चालू होने तक, लिखने के ऑपरेशन सूची में बने रहते हैं.

import { disableNetwork } from "firebase/firestore"; 

await disableNetwork(db);
console.log("Network disabled!");
// Do offline actions
// ...
firebase.firestore().disableNetwork()
    .then(() => {
        // Do offline actions
        // ...
    });
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
Firestore.firestore().disableNetwork { (error) in
  // Do offline things
  // ...
}
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
[[FIRFirestore firestore] disableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do offline actions
  // ...
}];
db.disableNetwork().addOnCompleteListener {
    // Do offline things
    // ...
}
db.disableNetwork()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Do offline things
                // ...
            }
        });
db.disableNetwork().then((_) {
  // Do offline things
});

नेटवर्क का ऐक्सेस फिर से चालू करने के लिए, यह तरीका अपनाएं:

import { enableNetwork } from "firebase/firestore"; 

await enableNetwork(db);
// Do online actions
// ...
firebase.firestore().enableNetwork()
    .then(() => {
        // Do online actions
        // ...
    });
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
Firestore.firestore().enableNetwork { (error) in
  // Do online things
  // ...
}
ध्यान दें: यह प्रॉडक्ट, watchOS और ऐप्लिकेशन क्लिप टारगेट पर उपलब्ध नहीं है.
[[FIRFirestore firestore] enableNetworkWithCompletion:^(NSError *_Nullable error) {
  // Do online actions
  // ...
}];
db.enableNetwork().addOnCompleteListener {
    // Do online things
    // ...
}
db.enableNetwork()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                // Do online things
                // ...
            }
        });
db.enableNetwork().then((_) {
  // Back online
});