Sunday 19 March 2017

Firebase querying - issue with indexing unique ids

My database structure looks like this (simplified):

{
  "articles": {
    "article1": {
      "title": "Article 1",
      "category": "news"
    },
    "article2": {
      "title": "Article 2",
      "category": "other"
    },
    "article3": {
      "title": "Article 3",
      "category": "news"
    },
    "article4": {
      "title": "Article 4",
      "category": "news"
    }
  },
  "articlesByCategory": {
    "news": {
      "article1": true,
      "article3": true,
      "article4": true
    },
    "other": {
      "article2": true
    }
  }
}

The query needs to fetch articles where a specific article's category isn't within. Does that make sense? Say, if article4 is of category "other", the query would only fetch articles within "news" and all other existing categories. But since the list may contain, say millions of articles, I have to be as specific as possible and not fetch articles that doesn't match this exact criteria. Therefor, a query like below would be ideal:

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

Here I am searching for categories where a specific property is absent (where a property equals to null). This is explained here: Firebase: Query to exclude data based on a condition

However, doing a query like this requires me to index every article's unique id on "/articlesByCategory" in the security rules. But it would be unrealistic and non-optimal to dynamically add new article ids inside the ".indexOn" array as that would end up with millions of unique (auto-generated) ids:

{
  "articles": {
    ".read": true,
    ".write": true
  },
  "articlesByCategory": {
    ".read": true,
    ".write": true,
    ".indexOn": ["article1", "article2", "article3", "article4"...] // List would be endless!
  }
}

So how is this achievable? Why am I seeing these sorts of structures (inverted indexing) as ideal solutions everywhere on StackOverflow, but no one seems to tackle this issue?



via Nordling Art

No comments:

Post a Comment