我正在使用Firestore来保存事务并按这样的时间戳字段查询数据。
CollectionReference IOTransactions = db.collection(userID)
.document("userData").collection("StockTransactions");
Query transactionsQuery = IOTransactions
.whereLessThan("timestamp", dateOfToday())
.whereGreaterThan("timestamp", findDaysAgo())
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(20);
transactionsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("FirestoreDemo", "Listen failed.", e);
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
Log.d(TAG, "New city: " + dc.getDocument().getData() + " |||| " +queryDocumentSnapshots.);
String doc_id = dc.getDocument().getId();
transactionsList.add(dc.getDocument().toObject(StockTransaction.class));
break;
case MODIFIED:
Log.d(TAG, "Modified city: " + dc.getDocument().getData());
break;
case REMOVED:
Log.d(TAG, "Removed city: " + dc.getDocument().getData());
transactionsList.remove(dc.getOldIndex());
adapter.notifyItemRemoved(dc.getOldIndex());
break;
}
}
我的问题是,如果将文档添加到集合中,我在Firestore控制台中看到该文档将结果中的所有文档都视为“文档读取”,而不仅仅是新添加的文档。我检查了它是否通过getMetaData()。isFromCache()方法使用了缓存,并且返回true。
但是,如果我删除where方法并使用
Query transactionsQuery = IOTransactions
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(20);
那么它仅计数1,这是新添加的文档。
我想查询时间戳,但是如果无法解决此计数问题,我将更改代码。