使用 firestore 和 Flutter 效率搜索唯一的用户名



我使用此代码使用 Firebase cloud-firestore 检查用户名是否唯一或存在于 firestore cloud 中,并且到目前为止它仍然可以正常工作,但是如果我有超过 10000 个用户名使用此代码进行检查会发生什么?

那么需要多少时间来检查数据库?以及您是否建议使用algolia或elasticSearch代替。

final QuerySnapshot result = await Future.value(Firestore.instance
.collection('check_username')
.where('username', isEqualTo: userNameController.text.toLowerCase())
.limit(1)
.getDocuments());
final List<DocumentSnapshot> documents = result.documents;
if (documents.length == 1) {
print("UserName Already Exits");
setState(() {
_userExist = documents.length == 1;
});
} else {
print("UserName is Available");
setState(() {
_userExist = documents.length == 1;
});
}```

Firestore 的一个有趣(也是非常独特(的技巧是读取操作的性能不依赖于集合中的文档数量。相反,它取决于您读取的数据量。

因此,在查询中,您正在检索单个文档:

final QuerySnapshot result = await Future.value(Firestore.instance
.collection('check_username')
.where('username', isEqualTo: userNameController.text.toLowerCase())
.limit(1)

对于性能,无论check_username中有 100 个文档、100,000 个文档还是 100,000,000 个文档,性能将始终相同。


也就是说,我建议使用用户名本身作为此集合中的键。这会自动确保每个用户名只能有一个文档,因为文档 ID 在其集合中必须是唯一的。

因此,如果您使用用户名作为文档 ID,则检查将变为:

final DocumentSnapshot result = await Future.value(Firestore.instance
.collection('check_username')
.document(userNameController.text.toLowerCase())
.get());
if (result.exists) {
print("UserName Already Exits");
} else {
print("UserName is Available");
}
setState(() {
_userExist = result.exists;
});

最新更新