Denormalizing your Data Store for Firebase
- 在Firebase上存的資料是jason的文件
- 資料項目是以key-value的格式表示,value的值可以是數字/字串/其他物件,但是不支援array。
- 當要建構Firebase資料庫時,記住下列兩個規則:
- 讓資料的階層淺一點(shallow)
- 不要怕重複的資料
- Firebase上的資料是以URL的方式來存取
- 若我建了一個主要的project叫`Uber for Dogs`,他就會存在於此網址:https://uber-for-dogs.firebaseio.com/
- 若我存了一個物件如下
{
name: 'Anthony'
}
- 那麼我就可以在 https://uber-for-dogs.firebaseio.com/name取得Anthony這個字串
- 假設資料更複雜一點如下,想要查詢某個user時只要去/users/some-user-id查詢還蠻方便。但若是想查詢某篇文章,而且資料內有很多個user,那就必須要查過所有user才能找到該篇文章。
users: {
tylermcginis: {
name: 'Tyler McGinnis',
age: 25,
posts: {
post1: {
title: 'What is a jQuery',
date: 1461131626103,
likes: {
'jakelingwall': true,
'eanplatter': true,
'mikenzi': true
},
replies: {
reply1: {
name: 'Jake Lingwall',
comment: 'Its a monad',
id: 'jakelingwall'
},
reply2: {
name: 'Ean Platter',
comment: 'Its a type of Java',
id: 'eanplatter'
}
}
}
}
}
}
- 你可以將資料改成下列格式,讓重複的資料來加快尋找特定文章的速度,但重複的資料又會有資料是否能sync的困難點。
users: {
tylermcginis: {
name: 'Tyler McGinnis',
age: 25,
posts: {
post1: {
title: 'What is a jQuery',
date: 1461131626103,
likes: {
'jakelingwall': true,
'eanplatter': true,
'mikenzi': true
},
replies: {
reply1: {
name: 'Jake Lingwall',
comment: 'Its a monad',
id: 'jakelingwall'
},
reply2: {
name: 'Ean Platter',
comment: 'Its a type of Java',
id: 'eanplatter'
}
}
}
}
}
},
posts: {
post1:{
title: 'What is a jQuery',
date: 1461131626103,
likes: {
'jakelingwall': true,
'eanplatter': true,
'mikenzi': true
},
replies: {
reply1: {
name: 'Jake Lingwall',
comment: 'Its a monad',
id: 'jakelingwall'
},
reply2: {
name: 'Ean Platter',
comment: 'Its a type of Java',
id: 'eanplatter'
}
}
}
}
- 下面的資料格式則是讓資料階層變很淺,並且把重複的資料移除,但要查詢某篇文章時,必須送出三個request (posts/replies/likes),所以這個方式也不是最好的
users: {
tylermcginis: {
name: 'Tyler McGinnis',
age: 25,
posts: {
post1: true,
}
}
},
posts: {
post1:{
title: 'What is a jQuery',
date: 1461131626103,
}
},
replies: {
post1: {
reply1: {
name: 'Jake Lingwall',
comment: 'Its a monad',
id: 'jakelingwall'
},
reply2: {
name: 'Ean Platter',
comment: 'Its a type of Java',
id: 'eanplatter'
}
}
},
likes: {
post1: {
'jakelingwall': true,
'eanplatter': true,
'mikenzi': true
}
}
users: {
tylermcginis: {
name: 'Tyler McGinnis',
age: 25,
posts: {
post1: true,
}
}
},
posts: {
post1:{
title: 'What is a jQuery',
date: 1461131626103,
likes: {
'jakelingwall': true,
'eanplatter': true,
'mikenzi': true
},
replies: {
post1: {
reply1: {
name: 'Jake Lingwall',
comment: 'Its a monad',
id: 'jakelingwall'
},
reply2: {
name: 'Ean Platter',
comment: 'Its a type of Java',
id: 'eanplatter'
}
}
},
}
}
- 這些trade-off的取捨,取決於你的AP的需要,根據你的需要來建構最佳的格式
沒有留言:
張貼留言