2017-01-13 39 views
0

火力地堡数据结构Firebase中的嵌套密钥查询?

{ 
    "books": { 
    "-KaKjMMw-WQltqxrGEmj": { 
     "categories": { 
     "cat1": true, 
     "cat2": true 
     }, 
     "author": "user1", 
     "title": "event1" 
    }, 
    "-KaKjMMw-WQltqxrGEmk": { 
     "categories": { 
     "cat1": true, 
     "cat2": false 
     }, 
     "author": "user1", 
     "title": "event2" 
    } 
    } 
} 

查询来查找特定作者的所有书籍

FNode.testNode.child("books") 
    .queryOrderedByChild("author") 
    .queryEqualToValue("user1") 
    .observeEventType(.Value) { (snapshot) in 
    print(snapshot) 
} 

问:

我想找到所有的属于到cat1。无法弄清楚这个问题。

+0

很抱歉更新了数据结构!稍微调整一下,通过更改键来隐藏我原来的数据目的。失败严重。我的错 ! :D –

回答

1

经过大量的打击和审判,终于得到了我的答案。

对于上述结构。如果你想找到所有的属于CAT1下面是该查询:

FNode.testNode.child("books") 
    .queryOrderedByChild("categories/cat1").queryEqualToValue(true) 
    .observeEventType(.Value) { (snapshot) in 
    print(snapshot) 
} 

注:FNode.testNode可能是类型的任何节点FIRDatabaseReference

致Firebase团队:您能否在数据结构中包含所有可能的Firebase查询样本,并将其与Firebase文档一起提供。现在对我们来说,这是一种屡试不爽的方式。

+1

这可行,但意味着您需要为每个类别[在Firebase安全规则中定义一个索引](https://firebase.google.com/docs/database/security/indexing-data)。对于更可维护的解决方案,请参阅我的答案:http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value –

+0

当然,这个链接。 –

+0

还有没有把索引放在数据库规则中查询的缺点是什么?它真的会很慢吗? –