从 Firestore 中选择随机文档 [英] Select random document from Firestore

查看:23
本文介绍了从 Firestore 中选择随机文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Cloud Firestore 的一个集合中有 1000 个文档,是否可以获取随机文档?

I have 1000 documents in a single collection in Cloud Firestore, is it possible to fetch random documents?

例如:Students 是 Firestore 中的一个集合,我在该集合中有 1000 名学生,我的要求是每次调用时随机挑选 10 名学生.

Say for example: Students is a collection in Firestore and I have 1000 students in that collection, my requirement is to pick 10 students randomnly on each call.

推荐答案

是的,要实现这一点,请使用以下代码:

Yes it is and to achieve this, please use the following code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference studentsCollectionReference = rootRef.collection("students");
studentsCollectionReference.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<Student> studentList = new ArrayList<>();
            for (DocumentSnapshot document : task.getResult()) {
                Student student = document.toObject(Student.class);
                studentList.add(student);
            }

            int studentListSize = studentList.size();
            List<Students> randomStudentList = new ArrayList<>();
            for(int i = 0; i < studentListSize; i++) {
                Student randomStudent = studentList.get(new Random().nextInt(studentListSize));
                if(!randomStudentList.contains(randomStudent)) {
                    randomStudentList.add(randomStudent);
                    if(randomStudentList.size() == 10) {
                        break;
                    }
                }
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

这称为经典解决方案,您可以将其用于仅包含少量记录的集合,但如果您害怕获得大量读取,我会向您推荐第二种方法.这还涉及通过添加一个新文档来对您的数据库进行一些更改,该文档可以包含一个包含所有学生 ID 的数组.因此,要获得那些随机的 10 个学生,您只需要进行一次 get() 调用,这意味着只有一次读取操作.获得该数组后,您可以使用相同的算法并获得这 10 个随机 ID.获得这些随机 ID 后,您就可以获取相应的文档并将它们添加到列表中.通过这种方式,您只需再执行 10 次读取即可获得实际的随机学生.总共只有 11 次文档读取.

This is called the classic solution and you can use it for collections that contain only a few records but if you are afraid of getting huge number of reads then, I'll recommend you this second approach. This also involves a little change in your database by adding a new document that can hold an array with all student ids. So to get those random 10 students, you'll need to make only a get() call, which implies only a single read operation. Once you get that array, you can use the same algorithm and get those 10 random ids. Once you have those random ids, you can get the corresponding documents and add them to a list. In this way you perform only 10 more reads to get the actual random students. In total, there are only 11 document reads.

这种做法称为反规范化(复制数据),是 Firebase 的常见做法.如果您是 NoSQL 数据库的新手,为了更好地理解,我建议您观看此视频,Firebase 数据库的非规范化是正常的.它适用于 Firebase 实时数据库,但同样的原则也适用于 Cloud Firestore.

This practice is called denormalization (duplicating data) and is a common practice when it comes to Firebase. If you're new to NoSQL database, so for a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database. It's for Firebase realtime database but same principles apply to Cloud Firestore.

但是请记住,您在这个新创建的节点中添加随机产品的方式与不再需要时需要删除它们的方式相同.

But rememebr, in the way you are adding the random products in this new created node, in the same way you need to remove them when there are not needed anymore.

要将学生 ID 添加到数组中,只需使用:

To add a student id to an array simply use:

FieldValue.arrayUnion("yourArrayProperty")

要删除学生证,请使用:

And to remove a student id, please use:

FieldValue.arrayRemove("yourArrayProperty")

要一次获取所有 10 个随机学生,您可以使用 List> 然后调用 Tasks.whenAllSuccess(tasks),如中所述我在这篇文章中的回答:

To get all 10 random students at once, you can use List<Task<DocumentSnapshot>> and then call Tasks.whenAllSuccess(tasks), as explained in my answer from this post:

这篇关于从 Firestore 中选择随机文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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