Firestore get()始终尝试首先从SERVER获取数据,即使我将CACHE添加到查询中,如何仅同步更新的文档?
根据有关启用脱机数据的官方文档:
对于Android和iOS,默认情况下启用离线持久性。
因此,要使用离线持久性,您无需对代码进行任何更改(“添加”)即可使用和访问Cloud Firestore数据。
同样根据有关Query的get()方法的官方文档:
默认情况下,get()尝试通过等待来自服务器的数据来尽可能地提供最新数据,但是如果您离线并且无法访问服务器,它可能会返回缓存的数据或失败。可以通过Source参数更改此行为。
因此,这是正常的行为。从2018-06-13(16.0.0
SDK)开始,现在可以指定我们要从中获取数据的来源。我们可以借助documentReference.get(Source
source)和Query.get(Source
source)方法来实现。
正如你所看到的,我们现在可以作为参数传递给
documentReference或给
Query源,以便我们可以强制数据的检索从
serveronly,
chache only或尝试服务器,并回落到缓存中。
因此,现在可以执行以下操作:
yourDocRef.get(Source.SERVER).addonSuccessListener(new OnSuccessListener<documentSnapshot>() { @Override public void onSuccess(documentSnapshot documentSnapshot) { //Get data from the documentSnapshot object }});在这种情况下,我们强制仅从服务器检索数据。如果要强制将只从缓存中检索数据,您应该作为参数传递给
get()方法,
Source.SERVER。更多信息在这里。
如果只想获取
updateddocuments,则可以查看快照之间的更改。官方文档中的示例为:
db.collection("cities") .whereEqualTo("state", "CA") .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot snapshots, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "listen:error", e); return; } for (documentChange dc : snapshots.getdocumentChanges()) { switch (dc.getType()) { case ADDED: Log.d(TAG, "New city: " + dc.getdocument().getData()); break; case MODIFIED: Log.d(TAG, "Modified city: " + dc.getdocument().getData()); break; case REMOVED: Log.d(TAG, "Removed city: " + dc.getdocument().getData()); break; } } } });看到每个特定情况的switch语句吗?第二种情况将帮助您仅获取更新的数据。
在我的Recyler视图中,我希望按字段日期而不是lut(last-modified-time)对数据进行排序
在这种情况下,您应该创建一个查询,该查询允许您按特定的日期属性对结果进行排序。假设您具有一个如下所示的数据库结构:
Firestore-root | --- items (collection) | --- itemId (document) | --- date: Oct 08, 2018 at 6:16:58 PM UTC+3 | --- //other properties
像这样的查询将帮助您实现:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();CollectionRefference itemsRef = rootRef.collection("items");Query query = itemsRef.orderBy("date", Query.Direction.ASCENDING);使用FireStore Snapshot Listener,我无法查询这么大的记录集。
哦,可以。根据此答案,Firebase可以有效遍历数十亿个项目。该答案适用于Firebase实时数据库,但相同的原理也适用于Cloud Firestore。



