2017-03-19 33 views
0

我的數據庫結構看起來像這樣(簡化):火力地堡查詢 - 問題與索引唯一ID

{ 
    "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作爲,將數以百萬計的獨特(自動生成)IDS結束:

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

那麼這是怎麼實現的?爲什麼我在StackOverflow的各處看到這些結構(倒排索引)是理想的解決方案,但似乎沒有人解決這個問題?

回答

0

火力地堡只能查詢與自動生成的ID節點順序發言,而當你定義自己的鑰匙,火力不能執行任何排序/訂貨

生成密鑰的理想方法是

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.getInstance().child("articles").orderByChild("category").equalTo("other"); 
+0

「文章1」,「文章」等都是唯一的ID。我已經在第一篇文章中將它們更改爲「-uniqueId1」等以便更好地理解。無論如何,您執行查詢的方式將在類別「其他」中獲取文章。這不是我想要做的。我想獲取_doesn't_屬於「其他」的文章,其中我必須通過「articlesByCategory」內的倒排索引進行查詢,查找不包含id爲「-uniqueId2」的文章的類別(因爲那個有類別「其他」)。 –