2017-05-06 26 views
0

我有一個NOSQL(Cloudant)數據庫如何做一個鏈接的NoSql查詢

-Within我們有文件的數據庫文件所在的領域之一,代表「表」(文檔類型)

-Within這些文件我們有代表鏈接其他文檔數據庫

內例如字段:

{_id: 111, table:main, user_id:222, field1:value1, other1_id: 333} 

{_id: 222, table:user, first:john, other2_id: 444} 

{_id: 333, table:other1, field2:value2} 

{_id: 444, table:other2, field3:value3} 

我們想要的搜索_id的方式:111

而且結果與數據某一文檔的鏈接表:

{_id:111, user_id:222, field1:value1, other1_id: 333, first:john, other2_id: 444, field2:value2, field3:value3} 

有沒有辦法做到這一點?
我們如何存儲或獲取數據的結構具有靈活性 - 關於如何更好地構造數據以使其成爲可能的任何建議?

回答

1

首先要說的是,Cloudant中沒有連接。如果你的模式依賴於大量的加入,那麼你正在對付Cloudant這可能意味着額外的複雜性或性能命中。

有一種方法可以在MapReduce視圖中取消引用其他文檔的ID。下面是它如何工作的:

  • 創建MapReduce的觀點發出主文檔的身體和其鏈接的文檔的IDS形式{ _id: 'linkedid'}
  • 查詢視圖與include_docs=true給拉了回來文檔和解除引用的IDS在一個去

在你的情況,地圖功能是這樣的:

function(doc) { 
    if (doc.table === 'main') { 
    emit(doc._id, doc); 
    if (doc.user_id) { 
     emit(doc._id + ':user', { _id: doc.user_id }); 
    } 
    } 
} 

將允許你拉回來m個艾因文件,通過敲擊GET /mydatabase/_design/mydesigndoc/_view/myview?startkey="111"&endkey="111z"&include_docs=true端點一個API其鏈接的用戶文檔:

{ 
    "total_rows": 2, 
    "offset": 0, 
    "rows": [ 
    { 
     "id": "111", 
     "key": "111", 
     "value": { 
     "_id": "111", 
     "_rev": "1-5791203eaa68b4bd1ce930565c7b008e", 
     "table": "main", 
     "user_id": "222", 
     "field1": "value1", 
     "other1_id": "333" 
     }, 
     "doc": { 
     "_id": "111", 
     "_rev": "1-5791203eaa68b4bd1ce930565c7b008e", 
     "table": "main", 
     "user_id": "222", 
     "field1": "value1", 
     "other1_id": "333" 
     } 
    }, 
    { 
     "id": "111", 
     "key": "111:user", 
     "value": { 
     "_id": "222" 
     }, 
     "doc": { 
     "_id": "222", 
     "_rev": "1-6a277581235ca01b11dfc0367e1fc8ca", 
     "table": "user", 
     "first": "john", 
     "other2_id": "444" 
     } 
    } 
    ] 
} 

通知我們如何得到兩排後面,第一個是主文檔正文,第二鏈接的用戶。