Select couchbase 嵌套对象

Select couchbase nested object

我有一堆结构如下的文档:

{
  "month": 11,
  "year": 2017,
  //other fields
  "Cars":[
  {
    "CarId": 123,
    // other fields
  },
  {
    "CarId": 456,
    // other fields
  }
  // other cars
   ]
}

我正在使用 id = 456 搜索具体的汽车实例。到目前为止我有:

SELECT Cars
FROM DevBucket
WHERE year = 2017
    AND month = 11
    AND [CarId=456]

Couchbase returns 正确的文档(其中包含目标汽车)。但是,输出包含文档中所有 Car 节点的数组,但我想要一辆车(就像我在上面的示例中使用 SELECT Cars[1]

搜索 couchbase 教程没有给我答案。有没有更好的方法?

使用 UNNEST clause 您可以执行 "a join of the nested array with its parent object." 这将为每个嵌套元素生成一个对象,其中包括作为顶级字段的嵌套元素,以及原始文档的其余部分 (嵌套元素,以及所有)。

当其父对象的月份和年份为 11/2017 时,此查询将检索 ID 为 456 的汽车。

SELECT car
FROM DevBucket db
UNNEST Cars car
WHERE car.CarId = 456 
    AND db.year = 2017
    AND db.month = 11;

创建此索引比使用主索引的查找速度更快:

CREATE INDEX cars_index 
    ON DevBucket(DISTINCT ARRAY car.CarId FOR car IN Cars END);

有关 UNNEST 的更多信息,请参阅 NEST and UNNEST: Normalizing and Denormalizing JSON on the Fly