首页 > 解决方案 > 如何优化此 Firestore 查询?

问题描述

我正在执行此查询以获取当前用户关注的用户的帖子[例如在社交媒体中]。但是这个查询花费了很多时间。正如你所看到的,我也将它们转换为发布实体并为每个设置它们的相应属性,我认为这是罪魁祸首。我该如何优化它?

我在firestore中为用户和帖子提供了不同的当前集合

suspend fun getPostsForProfile(uid: String) = withContext(Dispatchers.IO) {
        safeCall {
            Log.d(" basePostRepository ", " getPostsForProfile is called  ")
            val Currentuid = FirebaseAuth.getInstance().uid!!
            // get Posts where authorUid is equal to uid
            val profilePosts = posts.whereEqualTo("authorUid", uid)
                .orderBy("date", Query.Direction.DESCENDING)
                .get()
                .await()
                .toObjects(Post::class.java)
                .onEach { post ->
                    Log.d(" basepostRepository : getPostforProfile ", post.authorUid)
                    val user = getUser(post.authorUid).data!!
                    post.authorUsername = user.type
                    val  isLiked_init = post.likedBy.find { item -> item == Currentuid}
                    post.isLiked = when (isLiked_init) {
                        null -> false
                        else -> true
                    }
                }
            Resource.Success(profilePosts)
        }
    }


suspend fun getUser(uid: String) = withContext(Dispatchers.IO) {
        safeCall {
            val currentUid = FirebaseAuth.getInstance().uid!!
            val user = users.document(uid).get().await().toObject(User::class.java)
                ?: throw IllegalStateException()
            val currentUser = users.document(currentUid).get().await().toObject(User::class.java)
                ?: throw IllegalStateException()
            val  isfollowed_init = currentUser.follows.find { item -> item == uid}
            user.isfollowing = when (isfollowed_init) {
                null -> false
                else -> true
            }
            Resource.Success(user)
        }
    }

标签: androidfirebaseandroid-studiogoogle-cloud-firestore

解决方案


你可以做很多事情:

1 - 获取数据时,使用 Firestorelimit获取特定数量的帖子。理想情况下,比用户在通常的用户设备屏幕尺寸上所能看到的要多一点。可能 15 到 20 并且如果用户滚动加载更多。对于您知道其中包含大量数据的大多数查询,这是一种很好的方法。

2 - 将作者数据保存到帖子中,以避免通过单独的调用获取它(即使它是一个用户,也会一次又一次地进行相同的调用)也保存 athor uid。这样,您可以通过作者查询uid当前用户正在关注的内容,并避免获取所有帖子并在客户端过滤它们。

3 - 每次尝试获取帖子作者数据/用户时,不要调用当前用户关注的用户。将关注者保存在一个集合中,并在您的应用程序中使用实时侦听器调用他们一次。


推荐阅读