【问题标题】:How can i optimize this Firestore query?如何优化此 Firestore 查询?
【发布时间】:2021-09-09 22:07:26
【问题描述】:

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

我在 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)
        }
    }

【问题讨论】:

  • 找到解决办法了吗?
  • 我将 val user = getUser(post.authorUid) 移出循环,因为 post.authorUid 始终等于 uid。这有帮助。但在 getPostsforFollows() [代码未在此处上传] 我在优化方面没有运气。

标签: android firebase android-studio google-cloud-firestore


【解决方案1】:

你可以做很多事情:

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

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

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

【讨论】:

  • 我没有得到第三点。能详细点吗?
  • 您可以调用当前用户的关注者列表一次,并实时收听其变化。这样,您将大大减少应用程序中的读取量。假设一位用户有 500 个关注者。你会用你的方法多次阅读它们。
猜你喜欢
  • 2017-03-01
  • 2023-04-02
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多