如何改善这个简单查询的延迟?

时间:2018-01-05 08:51:04

标签: typescript firebase google-cloud-firestore

我在Firestore中拥有大约112k个城市的集合,我想使用下面的函数查找基于countryCode的城市。

如果我计时此功能,Firebase控制台中没有任何已配置的索引,则它的时间大约为1100毫秒。如果我在name和countryCode上创建索引排序,则该函数大约需要950毫秒。

我正在欧洲测试,服务器在美国。

这是预期的行为吗?什么是改善此查询延迟的最佳方法?

我可以在欧洲建立另一个数据库实例,但我怀疑它会产生巨大的差异。一个简单的id查找在同一个数据库上大约需要200ms,所以我预计至少800ms的时间与往返延迟无关。

async function getIdForCity(name: string, countryCode: string) {
  console.time("Get city id");
  const snapshot = await db
    .collection("cities")
    .where("name", "==", name)
    .where("countryCode", "==", countryCode)
    .get();

  if (snapshot.size === 0) {
    throw new Error(
      `Unable to find city with name ${name} and countryCode ${countryCode}`
    );
  }

  if (snapshot.size > 1) {
    throw new Error(
      `There are multiple (${
        snapshot.size
      }) cities with name ${name} and countryCode ${countryCode}`
    );
  }
  const cityId = snapshot.docs[0].id;
  console.timeEnd("Get city id");
  console.log(`City id for ${name}, ${countryCode}: ${cityId}`);
  return cityId;
}

0 个答案:

没有答案
相关问题