2010-06-17 59 views
2

說我有一個傳統的SQL結構,像這樣:傳統SQL VS的MongoDB/CouchDB的簡單的Python應用程序

create table tags (id PRIMARY KEY int, tag varchar(100)); 
create table files (id PRIMARY KEY int, filename varchar(500)); 
create table tagged_files (tag_id int, file_id int); 

我添加一些標籤:

insert into table tags (tag) values ('places'); 
insert into table tags (tag) values ('locations'); 

和一些文件:

insert into table files (filename) values ('/tmp/somefile'); 
insert into table files (filename) values ('/tmp/someotherfile'); 

然後標記這些文件:

insert into table tagged_files (tag_id, file_id) values (1,1); 
insert into table tagged_files (tag_id, file_id) values (1,2); 

然後,我可以找到標註了第一個標籤,像這樣的文件:

select * from files, tagged_files where id = file_id and tag_id = 1 

但我怎麼辦使用NoSQL的解決方案,如MongoDB的和CouchDB的同樣的事情?而NoSQL項目最適合這樣的事情?

回答

1

對於MongoDB。

有可能到頭來你會簡單地將它們保存與標籤爲:

db.Files.save({ "fn" : "/tmp/somefile", "ts" : [ { "t" : "places" }, { "t" : "locations" }] }); 
db.Files.save({ "fn" : "/tmp/someotherfile", "ts" : [ { "t" : "locations" }] }); 

選擇是單獨保存的標籤(的ObjectId的是12個字節IIRC):

db.Tags.save({ "t" : "places" }); 
db.Tags.save({ "t" : "locations" }); 
db.Files.save({ "fn" : "/tmp/somefile", "t" : [ { "i" : ObjectId("IdOfPlaces") }, { "i" : ObjectId("IdOfLocations") }] }); 

在這兩種情況下,獲得文件是

db.Files.find({ "_id" : ObjectId("4c19e79e244f000000007e0d") }); 
db.Files.find({ "fn" : "/tmp/somefile" }); 

或者幾個文件基於標籤:

db.Files.find({ ts : { t : "locations" } }) 
db.Files.find({ t : { i : ObjectId("4c19e79e244f000000007e0d") } }) 

示例來自mongo控制檯。如果你使用Id存儲標籤,你必須在獲得文件後根據Id的標籤讀取標籤。