比方说,我们有三种不同类型,GreatGrandma
,Grandma
,和Mom
。就像您想象的那样,他们的祖先关系看起来像这样。
- GreatGrandma
- Grandma
- Mom
由于我们不想将整个数据嵌套在单个JSON树中,因为它太大了,所以我们可能希望结构化的结构看起来像这样。
"greatGrandmas": {
"$great_grandma_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
}
}
"grandmas": {
"$great_grandma_key": {
"$grandma_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
}
}
}
"moms": {
"$great_grandma_key": {
"$grandma_key": {
"$mom_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
}
}
}
}
现在,我们要查询妈妈。如果我们认识曾祖母和祖母,那很容易。
firebase.database()
.ref('moms')
.child(greatGrandmaKey)
.child(grandmaKey);
.on('child_added', function (snapshot) { ... });
然后,我们可以添加一个大小限制或equalTo过滤器。
但是可以说,我们希望获得某个奶奶的所有妈妈类型。我们可以执行以下操作。
firebase.database()
.ref('moms')
.child(greatGrandmaKey)
.on('value', function (snapshot) { ... });
但是,我们将无法在此处应用任何过滤器。我们将被迫获取全部数据。这是不可扩展的。
如何建立Firebase数据库,以便可以查询具有完整或部分祖先路径的子代?
另外,我希望能够限制对整个树的访问,并且仅授予对某些Mom节点的访问权限。
在“妈妈”部分的示例中,您仍在创建一个深节点关系,这就是为什么您无法在妈妈节点中进行高效查询,并且即使您只希望数据的一小部分,也会得到大儿子的响应,有很多方法为了实现您想要的,有两种选择:
您可以为每种类型设置这样的引用,以便在这种情况下仅能调用所需的信息,即数据或类型的子代,如果您想在上游和下游查找关系,这将很有帮助:
"greatGrandmas": {
"$great_grandma_key": {
"data":{
"name": "Jane Smith",
"birthDate": "1970-01-01",
},
"grandmas":{
"$grandma_key":true
},
"moms":{
"$mom_key":true
}
}
}
"grandmas": {
"$grandma_key": {
"data":{
"name": "Jane Smith",
"birthDate": "1970-01-01",
},
"great_grandmas":{
"$great_grandma_key":true
},
"moms":{
"$mom_key":true
}
}
}
"moms": {
"$mom_key": {
"data":{
"name": "Jane Smith",
"birthDate": "1970-01-01",
},
"great_grandmas":{
"$great_grandma_key":true
},
"grandmas":{
"$grandma_key":true
}
}
}
在这种情况下,如果您只想从最低节点开始查找关系,那么您可以执行以下操作:
moms:{
"$mom_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
"great_grandma":$great_grandma_key
"grandma":$grandma_key
}
}
grandmas:{
"$grandma_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
"great_grandma":$great_grandma_key
}
}
great_grandmas:{
"$great_grandma_key": {
"name": "Jane Smith",
"birthDate": "1970-01-01"
}
}
在这种情况下,您只能通过特定的子节点值查询来获取关系,但是它只能在上游。
这取决于您如何查询和读取数据,谁将有权访问以及易于访问之间的平衡-vs-保持数据库一致的复杂性
查询将像:
REF_TO_MOM.orderByChild('grandma')。equalTo($ grandma_key).on('child_added',callback)
这个会让同一个奶奶的妈妈们
这是查询类型的引用以及如何使用它们
https://firebase.google.com/docs/database/android/retrieve-data#filtering_data
要获得与第一个结构相同的结果,可以执行以下操作:
MOMS_REF.child($mom_key).child('grandmas').on('child_added',function(snapshot){
//Here you only have the key of the mom's grandma so you can call a single event listener to get the rest of the data , this is a fairly common practice in firebase with very low network and data cost, to keep the data flow efficient i grouped the properties under a "data" node to avoid bringing unnecessary children in this call
GRANDMA_REF.child(snapshot.key).child('data').once('value',function(snap){
if(snap.val()){
//Here you can append to a dictionary or array the name, birthDate and the key of the grandmas of one mom.
}
})
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句