Firestore比较两个集合文档非常慢
我目前正在将移动用户的手机联系人上传到Firestore数据库。
平均而言,用户拥有约500个电话号码,我将拥有约1000个用户。
我的结构如下:
Firestore-root
|
--- users_contacts (collection)
|
--- uid (document)
|
--- contacts (subcollection)
|
--- phoneNumberOfContact (document)
|
--- phoneNumberOfContact: true
我有另一个集合,我存储一般电话号码,我想比较特定用户的联系人。
我在那里有大约50,000个电话号码,每个都是一个文件。这将在以后大大增加,可能达到100万。
Firestore-root
|
--- db_contacts (collection)
|
--- phoneNumber (document)
|
--- phoneNumber: true
我正在尝试检查特定已知uid和db_contacts集合的常用数字。 db_contacts集合中存在多少个已知的uid。
我的云功能如下:
- 获取联系人的所有电话号码 首先,我想只获取用户文档的ID,因为id是电话号码,希望它能使进程更快。但似乎在Javascript中不可能,因为snapshotChanges()不存在。
- 循环获取的联系人并检查db_contacts中是否存在联系人。因为我已经知道检查它是否存在的参考路径,所以这应该很快
- 返回所有常用联系人
如果JavaScript中有snapshotChanges()的替代方法,我的脚本运行速度会快得多。我的思维方式是否正确?
到目前为止我做了什么:
exports.findCommonNumbers = functions.https.onCall((data, context) => {
return new Promise((resolve, reject) => {
fetchCommonNumbers().then((commonNumbers) => {
console.log(commonNumbers);
resolve("Done");
}).catch((err) => {
console.log(err);
reject("Error Occured");
});
});
});
async function fetchCommonNumbers() {
var commonNumbers = [];
let contactsReference = admin.firestore().collection("user_contacts").doc("iNaYVsDCg3PWsDu67h75xZ9v2vh1").collection("contacts");
const dbContactReference = admin.firestore().collection('db_contacts');
userContacts = await contactsReference.get();
userContacts = userContacts.docs;
for(var i in userContacts){
var userContact = userContacts[i];
const DocumentID = userContact.ref.id;
//Check if Document exist
dbContact = await dbContactReference.doc(DocumentID).get();
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
}
return Promise.resolve(commonNumbers);
}
findCommonNumbers函数需要60秒才能执行。它必须快得多。我怎样才能让它更快?
回答如下:当你正在寻找共同的文件时,你正在拿一个,等待它回来,拿下下一个,等待它......我之前没有使用async / await,但是我会做类似的事情:
Promise.All(userContacts.map(userContact => {
const DocumentID = userContact.ref.id;
//Check if Document exists
return dbContactReference.doc(DocumentID).get().then(dbContact => {
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
});
}));
对不起代码碎片和错误;我在移动设备上。这应该立即请求所有人。
编辑:在返回所有其他内容后返回:
new Promise((resolve, reject) => {
var returned = 0;
userContacts.map(userContact => {
const DocumentID = userContact.ref.id;
//Check if Document exists
dbContactReference.doc(DocumentID).get().then(dbContact => {
if (dbContact.exists) {
commonNumbers.push(DocumentID);
}
returned++;
if (returned == userContact.length || commonNumbers.length >= 5) {
resolve(commonNumbers);
}
});
});
});