如何计算 Firestore 集合下的文档数量? [英] How to count the number of documents under a collection in Firestore?

查看:40
本文介绍了如何计算 Firestore 集合下的文档数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 CollectionReferenceCloud Firestore 上存在的计数,我尝试通过以下方式获取它:

FirebaseFirestore db = FirebaseFirestore.getInstance();最终 CollectionReference postsCollection = db.collection("Posts");final TaskCompletionSourcesource = new TaskCompletionSource<>();新线程(新运行(){@覆盖公共无效运行(){int fromWhereToStart = postsCollection.get().getResult().size();source.setResult(fromWhereToStart);}}).开始();任务<整数>任务 = source.getTask();task.addOnCompleteListener(new OnCompleteListener() {@覆盖public void onComplete(@NonNull Task task) {Log.e("Z_fromWhereToStart", "= " + task.getResult());}});

但不幸的是,我得到了:

java.lang.IllegalStateException:任务尚未完成

是否有另一种方法可以获得另一种修复IllegalStateException的方法的计数?

解决方案

2021 年 7 月 10 日

最近,Firebase 添加了一个名为分布式计数器的新扩展程序::><块引用>

使用此扩展程序为您的应用添加高度可扩展的计数器服务.这非常适合计算病毒式操作或任何非常高速的操作(例如观看次数、喜欢或分享)的应用程序.

使用此扩展,您还可以突破每秒一次写入操作的最大限制.

这里还有一篇您可能感兴趣的文章:


因为没有像我们在 Firebase 实时数据库中那样的 getDocumentCount() 方法,一个 getChildrenCount() 方法来实际计算 getDocumentCount() 下的所有文档的数量您的 Cloud Firestore 中的 code>Posts 集合,请使用以下代码:

db.collection(Posts").get().addOnCompleteListener(new OnCompleteListener() {@覆盖public void onComplete(@NonNull Task task) {如果(任务.isSuccessful()){整数计数 = 0;for (DocumentSnapshot 文档:task.getResult()) {计数++;}Log.d("TAG", count + "");} 别的 {Log.d(TAG, "获取文档时出错:", task.getException());}}});

db.collection(Posts").get().addOnCompleteListener(new OnCompleteListener() {@覆盖public void onComplete(@NonNull Task task) {如果(任务.isSuccessful()){Log.d("TAG", task.getResult().size() + "");} 别的 {Log.d(TAG, "获取文档时出错:", task.getException());}}});

上面的例子对于小数据集来说已经足够好了,但如果数据集更大就行不通了.但是,您还可以通过另外两种方式实现相同的目标.

一种方法是使用云函数来更新计数器 每次从 Posts 集合中添加或删除文档时.这种技术也适用于大数据集.但请注意,在这种情况下,文档的添加和删除只能以小于或等于每秒 1 次的速率发生,如 Cloud Firestore 配额和限制.这是一个要阅读的单个文档,但它几乎可以立即显示当前计数.

如果您需要超出此限制,则需要按照 分布式计数器的官方文档.

<块引用>

作为个人提示,不要在 Cloud Firestore 中存储这种计数器,因为每次增加或减少计数器都会花费您一次 readwrite 操作.在 Firebase Realtime 数据库中托管此计数器几乎免费.

第二种方法是在您添加或删除文档的同时更新计数器,而不是使用 Cloud Functions,而是在您的客户端使用事务.这样,您的计数器也会准确,因为它是同时更新的.但最重要的是,在这种情况下,您需要确保在添加或删除文档的任何位置都包含此逻辑.在这种情况下,您也可以免费使用 Firebase 实时数据库.

总而言之,对于小数据集使用第一个代码,第二个使用 Cloud Functions 因为是写入时尽力而为,第三个使用我在上面向您解释的最后一个选项.

I am trying to get CollectionReference count that exists on the Cloud Firestore, I have tried to get it with:

FirebaseFirestore db = FirebaseFirestore.getInstance();
    final CollectionReference postsCollection = db.collection("Posts");

    final TaskCompletionSource<Integer> source = new TaskCompletionSource<>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            int fromWhereToStart = postsCollection.get().getResult().size();
            source.setResult(fromWhereToStart);
        }
    }).start();

    Task<Integer> task = source.getTask();
    task.addOnCompleteListener(new OnCompleteListener<Integer>() {
        @Override
        public void onComplete(@NonNull Task<Integer> task) {
            Log.e("Z_fromWhereToStart", "= " + task.getResult());
        }
    });

But unfortunately, I'm getting:

java.lang.IllegalStateException: Task is not yet complete

Is there is another way to get the count of another way to fix the IllegalStateException?

解决方案

Edit: July 10th, 2021

Recently, Firebase added a new Extension called Distributed Counter:

Use this extension to add a highly scalable counter service to your app. This is ideal for applications that count viral actions or any very high-velocity action such as views, likes, or shares.

Using this Extension, you can also get over the max limit of one write operation/second.

Here is also an article that you might be interested in:


Becasue there is no getDocumentCount() method as we have in Firebase Realtime database, a getChildrenCount() method, to actually count the number of all documents beneath your Posts collection from your Cloud Firestore, please use the following code:

db.collection("Posts").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            int count = 0;
            for (DocumentSnapshot document : task.getResult()) {
                count++;
            }
            Log.d("TAG", count + "");
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

or

db.collection("Posts").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", task.getResult().size() + "");
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

The above examples work well enough for small datasets but it doesn't work if the dataset is larger. But, there are also two more ways in which you can achieve the same thing.

One way would be to use Cloud Functions to update a counter every time you add or delete a document from your Posts collection. This technique works well also for big datasets. But note, in this case, the additions and deletions of documents can only occur at the rate less than or equal to 1 per second, as described in Cloud Firestore Quotas and Limits. That is a single document to read but it shows you the current count almost instantly.

If there is a need for you to exceed this limitation, you need to implement distributed counters as explained in the official documentation of distributed counters.

As a personal hint, don't store this kind of counter in Cloud Firestore, because every time you increase or decrease the counter will cost you a read or a write operation. Host this counter in the Firebase Realtime database almost at no cost.

The second way would be, rather than using Cloud Functions, to use transactions at your client-side, to update the counter at the same time as you add or delete a document. In this way, your counter will also be accurate, because it is updated at the same time. But the most important thing, in this case, is that you'll need to make sure to include this logic anywhere you add or delete a document. You can use in this case Firebase Realtime database as well, at no cost.

In conclusion, use the first code for small datasets, the second use Cloud Functions because is write-time best-effort, and the third use the last option I have explained to you above.

这篇关于如何计算 Firestore 集合下的文档数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆