【问题标题】:How to do a NoSql linked query如何进行 NoSql 链接查询
【发布时间】:2017-06-24 14:12:00
【问题描述】:

我有一个 noSql (Cloudant) 数据库

-在数据库中,我们有文档,其中一个文档字段代表“表格”(文档类型)

-在文档中,我们有表示链接数据库中其他文档的字段

例如:

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

有没有办法做到这一点?
我们如何存储或取回数据的结构具有灵活性——关于如何更好地构建数据以使其成为可能的任何建议?

【问题讨论】:

    标签: cloudant


    【解决方案1】:

    首先要说的是,Cloudant 中没有连接。如果您的架构依赖于大量加入,那么您正在与 Cloudant 的颗粒背道而驰,这可能会给您带来额外的复杂性或性能损失。

    有一种方法可以在 MapReduce 视图中取消引用其他文档的 ID。以下是它的工作原理:

    • 创建一个 MapReduce 视图,以{ _id: 'linkedid'} 的形式发出主文档的正文及其链接文档的 ID
    • 使用include_docs=true 查询视图以一次性拉回文档和取消引用的ID

    在你的情况下,像这样的地图功能:

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

    将允许您通过点击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"
          }
        }
      ]
    }
    

    注意我们如何返回两行,第一行是主文档正文,第二行是链接用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多