我想在过去7天内查询云firestore数据。我正在使用Firestore的服务器时间戳也将时间存储在Millis中。
CollectionReference IOTransactions = db.collection(userID)
.document("userData").collection("StockTransactions");
Query transactionsQuery = IOTransactions.orderBy("timestamp",Query.Direction.DESCENDING);
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 (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
if (doc.get("timestamp") != null)
transactionsList.add(doc.toObject(StockTransaction.class));
Log.d("Firestore", "Added item");
}
if(transactionsList.size() < 1 )
emptyTransactionsPage.setVisibility(View.VISIBLE);
Log.d("Firestore Reading", "Successfully fetched");
adapter.notifyDataSetChanged();
pb.setVisibility(View.INVISIBLE);
}
});
我如何查询最近7天内创建的数据?
我正在使用firestore的服务器时间戳也将时间存储在毫秒中。
因此,如果您将时间戳存储在毫秒中,则做错了。
我如何查询过去7天内创建的数据。
为了根据时间的时间询问您的数据库,您的时间戳属性应为o类型Date
和 long。要查看如何实现这一目标,请从此 post 中查看我的答案。
正确设置属性后,看起来像这样的查询应该可以解决问题:
IOTransactions.whereLessThan("timestamp", now).whereGreaterThan("timestamp", sevenDayAgo);
now
和 sevenDayAgo
是两个Date
对象,代表当前时间和七天前的时间。
根据我的知识,您也可以使用以下查询来获取结果
Query query = mdb.collection("$YOUR_COLLECTION_NAME").orderBy("$YOUR_FIELD")
.whereGreaterThan("$YOUR_FIELD",$Begin_Date_Object)
.endAt($YOUR_DATE_OBJECT);
注意:您需要声明 java.util.date 对象到endat字段和Orderby必须始终是startat()或endat()方法。
搜索的结尾所有文档中包含字段值的结尾