I am using firestore to save transactions and querying data by timestamp field like that.
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;
}
}
My problem is that if a document added to collection, I see in the Firestore console that it counts all documents in the result as "document reads", not only new added document. I checked does it use cache with getMetaData().isFromCache() method and it returns true.
However if I delete where methods and use like that
Query transactionsQuery = IOTransactions
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(20);
then it counts only 1 which is new added document.
I want to query with timestamp but if I can't solve this counting problem I will change my code.