N1QL 在对象内搜索某些对象

N1QL search certain objects within the object

我的 couchbase 存储桶中有多个文档,结构如下:

{
  "objectType": "someObjectType",
  "id": "1",
  "latest": {
    "id": "1",
    "version": "biyr4jqi4nny"
  },
  "history": {
    "bi11b295bjng": {
      "id": "1",
      "version": "bi11b295bjng"
    }
    "bi1189wx1h6v": {
      "id": "1",
      "version": "bi1189wx1h6v"
    }
  }
}

如上面的代码片段所示,历史是对象的对象。我要做的是选择 objectType、id、latest 和 history,但 history 应该只包括查询中指定的对象,而不是所有历史记录(可能很大)。

我的查询如下所示:

SELECT
    bucket.id, 
    bucket.objectType, 
    bucket.latest, 
    bucket.history.bi11b295bjng
FROM bucket WHERE objectType = 'someObjectType'

这会产生以下响应:

[
  {
    "objectType": "someObjectType",
    "id": 1,
    "latest": {
      "id": "9mobile_NG_001-ROW",
      "version": "biyr4jqi4nny"
    },
    "biyr4jqi4nny": {
      "id": "1",
      "version": "biyr4jqi4nny"
    }
  }
]

查询的对象已从父对象中解包。所需的输出应如下所示:

[
  {
    "objectType": "someObjectType",
    "id": 1,
    "latest": {
      "id": "9mobile_NG_001-ROW",
      "version": "biyr4jqi4nny"
    },
    "history": {
      "biyr4jqi4nny": {
        "id": "1",
        "version": "biyr4jqi4nny"
      }
    }
  }
]

如何在不丢失父对象的情况下获取 history.{version}?

构造对象和别名作为历史记录

SELECT
    b.id, 
    b.objectType, 
    b.latest, 
    { b.history.bi11b295bjng } AS history
FROM bucket AS b 
WHERE b.objectType = "someObjectType";

如果需要同一字段的多个对象

SELECT
    b.id, 
    b.objectType, 
    b.latest, 
    { b.history.bi11b295bjng, b.history.bi1189wx1h6v } AS history
FROM bucket AS b 
WHERE b.objectType = "someObjectType";

如果你有很多想要删除其中一个

SELECT
    b.id, 
    b.objectType, 
    b.latest, 
    OBJECT_REMOVE(b.history,"bi11b295bjng") AS history
FROM bucket AS b 
WHERE b.objectType = "someObjectType";