How to do a NoSql linked query

China☆狼群 提交于 2019-12-25 09:43:58

问题


I have a noSql (Cloudant) database

-Within the database we have documents where one of the document fields represents “table” (type of document)

-Within the documents we have fields that represent links other documents within the database

For example:

{_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}

We want of way of searching for _id:111

And the result be one document with data from linked tables:

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

Is there a way to do this?
There is flexibility on the structure of how we store or get the data back—any suggestions on how to better structure the data to make this possible?


回答1:


The first thing to say is that there are no joins in Cloudant. If you're schema relies on lots of joining then you're working against the grain of Cloudant which may mean extra complication for you or performance hits.

There is a way to de-reference other documents' ids in a MapReduce view. Here's how it works:

  • create a MapReduce view to emit the main document's body and its linked document's ids in the form { _id: 'linkedid'}
  • query the view with include_docs=true to pull back the document AND the de-referenced ids in one go

In your case, a map function like this:

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

would allow you to pull back the main document and its linked user document in one API by hitting the GET /mydatabase/_design/mydesigndoc/_view/myview?startkey="111"&endkey="111z"&include_docs=true endpoint:

{
  "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"
      }
    }
  ]
}

Notice how we get two rows back, the first is the main document body, the second the linked user.



来源:https://stackoverflow.com/questions/43825864/how-to-do-a-nosql-linked-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!