【问题标题】:How can I prevent having multiple combinations of Firestore Indexes如何防止多个 Firestore 索引组合
【发布时间】:2021-10-30 22:38:43
【问题描述】:

基本上,我有一个来自 Firestore 的查询,并且某些过滤器字段可能为空,在这种情况下,特定查询将被忽略,由于具有多个字段的不等式查询需要索引,那么创建此类索引的最佳方法是什么查询而不经过所有可能的组合。

例如,'country' 和 'budget_high'、'gender' 和 'budget_high'、'age' 和 'budget_high'、'country、gender' 和 'budget_high' 等等。

这是我的查询。

if (country !== "") query = query.where("country", "==", country);
  if (gender !== "") query = query.where("gender", "==", gender);
  if (age !== "") query = query.where("age", "==", age);
  if (religion !== "") query = query.where("religion", "==", religion);
  if (budget_high !== "") query = query.where("budget_high", "<=", Number(budget_high));
  return query
    .get()
    .then((querySnapshot) => {
      var data = [];
      querySnapshot.forEach((doc) => {
        let user_data = doc.data();
        user_data.created_at = `${user_data.created_at.toDate()}`;
        data.push(user_data);
      });
      return data;
    })
    .catch((error) => {
      console.log("Error getting documents: ", error);
      return [];
    });
};

这是我收集的单字段豁免(不是收集组)

【问题讨论】:

标签: javascript reactjs firebase google-cloud-platform google-cloud-firestore


【解决方案1】:

首先,我们需要一个将出现在所有查询中的字段。您可以 orderBy 字段之一以使其始终存在(在这种情况下为budget_high,因为您正在对其调用不等式查询)。

所以创建 4 个复合索引。

  1. budget_high 和国家/地区 ASC
  2. budget_high 和性别 ASC
  3. budget_high 和年龄 ASC
  4. budget_high 和宗教 ASC

这将有效地处理您的查询组合。

阅读merging index docs

【讨论】:

  • 你的意思是单字段豁免?,因为我创建了复合索引并且销售不起作用。
  • 是的,这 5 个单字段豁免。
  • 等待...单字段索引...不是单字段豁免(不适用于集合组)。您可以阅读我附加的文档。
  • 我已经阅读了文档,但我仍然无法弄清楚。您只能在单个字段索引选项卡上创建豁免,我已经为集合(而不是组)创建了它仍然无法正常工作。我还附上了一张你可以看到的图片。
  • 好的。你想用什么来订购结果?假设它是 x。所以现在,您创建了 5 个复合索引,x 和国家、x 和性别、x 和年龄、x 和宗教、x 和budget_high。都可以是ASC。然后运行您的查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
相关资源
最近更新 更多