英文:
Problem with .whereField and Int during a Firestore request
问题
问题是:在下面的函数中,.whereField("likes", isGreaterThan: 0)
不起作用。我不明白为什么,因为.whereField("likes", isEqualTo: 0)
起作用。
有人能解释一下吗?
func fecthUserLikedTweets(forUid uid: String, completion: @escaping ([Tweet]) -> Void) {
Firestore.firestore().collection("tweets")
.whereField("likes", isGreaterThan: 0)
.whereField("uid", isEqualTo: uid)
.getDocuments { (snapshot, _) in
guard let document = snapshot?.documents else { return }
let tweets = document.compactMap { try? $0.data(as: Tweet.self) }
completion(tweets.sorted(by: { $0.timestamp.dateValue() > $1.timestamp.dateValue() }))
}
}
英文:
The problem is: .whereField("likes", isGreaterThan : 0)
does not work in the function below . I don't understand why because .whereField ("likes",isEqualTo : 0)
works.
Does anyone has an explanation for that?
func fecthUserLikedTweets(forUid uid: String, completion:@escaping([Tweet]) -> Void) {
Firestore.firestore().collection("tweets")
.whereField ("likes",isGreaterThan : 0)
.whereField("uid",isEqualTo:uid)
.getDocuments { (snapshot, _ ) in
guard let document = snapshot?.documents else {return}
let tweets = document.compactMap ({try? $0.data(as: Tweet.self)})
completion(tweets.sorted(by:{ $0.timestamp.dateValue() > $1.timestamp.dateValue() }))
}
}
答案1
得分: 1
您可能缺少查询所需的必要复合索引。
对于仅包含相等检查(isEqualTo
)的查询,Firestore 可以基于默认生成的单字段索引来满足它们。
一旦您使用了关系运算符(>
、<
等),您需要添加一个包含查询使用的确切字段的复合索引到您的数据库中。
添加这样的索引的最简单方法是捕获并记录代码中的错误,然后查找错误消息中的 URL 来创建索引。
英文:
You're probably missing a necessary composite index for the query.
For a query only consisting of equality checks (isEqualTo
), Firestore can fulfill them based on the single-field indexes that it generates by default.
Once you use a relational operator (>
, <
, etc) you need to add an additional composite index to your database with the exact fields that your query uses.
The easiest way to add such an index is to catch and log errors in your code, and then find the URL in the error message to create the index.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论