在Firestore中,可以使用orderBy()
和limit()
方法来按照时间戳对数据进行排序和限制。下面是一个使用Python的示例代码:
from google.cloud import firestore
def get_last_10_documents(collection_name):
# 初始化Firestore客户端
db = firestore.Client()
# 获取指定集合的引用
collection_ref = db.collection(collection_name)
# 按照时间戳对数据进行排序,并限制最后10个
query = collection_ref.order_by('timestamp', direction=firestore.Query.DESCENDING).limit(10)
# 执行查询
documents = query.get()
# 遍历结果
for doc in documents:
print(f'{doc.id} => {doc.to_dict()}')
# 使用示例
get_last_10_documents('your_collection_name')
上述代码中,首先通过firestore.Client()
方法初始化一个Firestore客户端。然后,使用db.collection(collection_name)
方法获取指定集合的引用。接下来,使用order_by()
方法将数据按照时间戳字段进行降序排序,并使用limit()
方法限制结果为最后10个。最后,通过get()
方法执行查询,并遍历结果打印出每个文档的ID和内容。
请注意,上述示例中的your_collection_name
需要替换为你自己的集合名称。此外,你还需要安装Google Cloud SDK并设置认证凭据,以便进行Firestore的连接和身份验证。