問題描述
我正在尋找為照片庫的 NoSQL 存儲構建合適的數據結構.在我的 Web 應用程序中,一張照片可以是 1 個或多個相冊的一部分.我有使用 MySQL 的經驗,但幾乎沒有使用過鍵值存儲.
I'm looking to build an appropriate data structure for NoSQL storage of a photo gallery. In my web application, a photo can be part of 1 or more albums. I have experience with MySQL, but almost none with key-value storage.
使用 MySQL,我將設置 (3) 個表,如下所示:
With MySQL, I would have set up (3) tables as follows:
photos (photo_id, title, date_uploaded, filename)
albums (album_id, title, photo_id)
album_photo_map (photo_id, album_id)
然后,要檢索 5 張最新照片的列表(帶有相冊數據),查詢如下:
And then, to retrieve a list of the 5 latest photos (with album data), a query like this:
SELECT *
FROM albums, photos, album_photo_map
WHERE albums.album_id = album_photo_map.album_id AND
photos.photo_id = album_photo_map.photo_id
ORDER BY photos.date_uploaded DESC LIMIT 5;
如何使用 NoSQL 鍵值對數據庫完成類似的查詢?(特別是亞馬遜的 DynamoDB.)存儲會是什么樣子?索引如何工作?
How would I accomplish a similar query using a NoSQL key-value pair database? (Specifically, Amazon's DynamoDB.) What would the storage look like? How would the indexing work?
推薦答案
使用 mongodb lingo,您的集合可能如下所示:
Using mongodb lingo, your collections could look like this:
photos = [
{
_id: ObjectId(...),
title: "...",
date_uploaded: Date(...),
albums: [
ObjectId(...),
...
]
},
...
]
albums = [
{
_id: ObjectId(...),
title: "..."
}
]
查找 5 張最新照片的方法如下:
Finding the 5 newest photos would be done like this:
> var latest = db.photos.find({}).sort({date_uploaded:1}).limit(5);
mongo 中沒有服務器端連接,因此您必須像這樣獲取所有最新專輯:
There's no server-side joins in mongo, so you'd have to fetch all the latest albums like this:
> var latest_albums = latest.find({}, {albums: 1});
當然,那你必須把它歸結為一個集合.
Of course, then you have to boil this down into a set.
如果您只是將相冊嵌入照片文檔中,實際上會更容易,因為它們很小:
It's actually easier if you just embed the album inside the photo documents, since they're small:
photos = [
{
_id: ObjectId(...),
title: "...",
date_uploaded: Date(...),
albums: [
{name: "family-vacation-2011", title: "My family vacation in 2010"},
...
]
},
...
]
那么查詢也是一樣的,只是你不必加入.查找相冊中的所有照片如下所示:
Then querying is the same, but you don't have to join. Finding all photos in an album looks like:
> db.photos.find({albums:{$elemMatch:{name: "family-vacation-2011"}}});
這篇關于用于 Web 照片庫的正確 NoSQL 數據架構的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!