【问题标题】:Firebase querying - issue with indexing unique idsFirebase 查询 - 索引唯一 ID 的问题
【发布时间】:2017-03-19 22:01:37
【问题描述】:

我的数据库结构如下(简化):

{
  "articles": {
    "-uniqueId1": {
      "title": "Article 1",
      "category": "news"
    },
    "-uniqueId2": {
      "title": "Article 2",
      "category": "other"
    },
    "-uniqueId3": {
      "title": "Article 3",
      "category": "news"
    },
    "-uniqueId4": {
      "title": "Article 4",
      "category": "news"
    }
  },
  "articlesByCategory": {
    "news": {
      "-uniqueId1": true,
      "-uniqueId3": true,
      "-uniqueId4": true
    },
    "other": {
      "-uniqueId2": true
    }
  }
}

查询需要获取特定文章类别不在其中的文章。那有意义吗?假设uniqueId2 属于“其他”类别,则查询将仅获取“新闻”和所有其他现有类别中的文章。但是由于该列表可能包含数百万篇文章,因此我必须尽可能具体,并且不要获取与此确切标准不匹配的文章。因此,理想的查询如下:

const ref = firebase.database().ref("articlesByCategory");
ref.orderByChild("-uniqueId2").equalTo(null).once("value", function(snapshot) {
  console.log(snapshot.key);
});

在这里,我正在搜索不存在特定属性的类别(其中属性等于null)。这在这里解释:Firebase: Query to exclude data based on a condition

但是,执行这样的查询需要我在安全规则中的“/articlesByCategory”上为每篇文章的唯一 ID 编制索引。但是,在“.indexOn”数组中动态添加新的文章 ID 是不切实际且非最佳的,因为这最终会产生数百万个唯一(自动生成)的 ID:

{
  "articles": {
    ".read": true,
    ".write": true
  },
  "articlesByCategory": {
    ".read": true,
    ".write": true,
    ".indexOn": ["-uniqueId1", "-uniqueId2", "-uniqueId3", "-uniqueId4"...] // List would be endless!
  }
}

那么这是如何实现的呢?为什么我在 StackOverflow 上到处都将这类结构(倒排索引)视为理想的解决方案,但似乎没有人解决这个问题?

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database


    【解决方案1】:

    Firebase 只能在具有自动生成 ID 的节点上查询订单语句,并且当您定义自己的键时,Firebase 无法执行任何排序/排序

    生成密钥的理想方式是

    firebase.getInstance().getReference("articles").push(myArticle);
    

    这将导致数据库结构略有不同,例如

    {
    "12dakj137_9": { // this is a auto-generated id
    "article1": {
      "title": "Article 1",
      "category": "news"
    },
    "12asjh_123": {
      "title": "Article 2",
      "category": "other"
    },...
    }
    

    现在 firebase 可以进行排序/排序,您可以通过

    firebase.getInstance().child("articles").orderByChild("category").equalTo("other");
    

    【讨论】:

    • "article1"、"article" 等是唯一 ID。为了更好地理解,我在第一篇文章中将它们更改为“-uniqueId1”等。无论如何,您进行查询的方式将获取“其他”类别中的文章。这不是我想要做的。我想获取 属于“其他”的文章,其中我必须通过“articlesByCategory”中的倒排索引查询,查找不包含 id 文章的类别“ -uniqueId2"(因为它具有“其他”类别)。
    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2014-10-01
    • 2022-08-05
    • 2020-04-28
    相关资源
    最近更新 更多