如何使用n1ql将变量传递给Subquery?

时间:2016-12-14 14:36:18

标签: couchbase n1ql

在我的情况下,entreprise(公司)可以拥有多个网站(filiales),我希望得到所有格式数组的filiales。

在json entreprise(公司),没有网站信息(filiales),在json网站(filiales),它有企业(公司)uid。 Json entreprise(公司):

{
  "type": "entreprise",
  "dateUpdate": 1481716305279,
  "owner": {
    "type": "user",
    "uid": "PNnqarPqSdaxmEJ4DoMv-A"
  }
}

Json网站(filiales):

  {
  "type": "site",
  "entreprise": {
    "uid": "3c0CstzsTjqPdycL5yYzJQ",
    "type": "entreprise"
  },
  "nom": "test"
}

我试过的查询:

  SELECT 
          META(entreprise).id as uid, 
          ARRAY s FOR s IN (SELECT d.* FROM default d  WHERE d.type = "site" AND  d.entreprise.uid = uid) END as sites, 
          entreprise.* 
        FROM default entreprise 
        WHERE entreprise.type = "entreprise";

结果:错误

 {
    "code": 5010,
    "msg": "Error evaluating projection. - cause: FROM in correlated subquery must have USE KEYS clause: FROM default."
  }

然后我使用别名:

SELECT 
  META(entreprise).id as uid, 
  ARRAY s FOR s IN (SELECT d.* FROM default d  WHERE d.type = "site" AND  d.entreprise.uid = META(entreprise).id) END as sites, 
  entreprise.* 
FROM default entreprise 
WHERE entreprise.type = "entreprise";

结果:sites数组为空。

2 个答案:

答案 0 :(得分:3)

首先,您必须在站点文档上创建索引:

CREATE INDEX site_ent_idx ON default(entreprise.uid) WHERE type="site";

然后更改您的查询以使用新索引:

SELECT 
META(entreprise).id as uid, 
ARRAY s FOR s IN (
    SELECT site.* 
    FROM default as ent USE KEYS META(entreprise).id 
    JOIN default as site ON KEY site.entreprise.uid FOR ent
) END as sites, 
entreprise.* 
FROM default entreprise 
WHERE entreprise.type = "entreprise"

此解决方案应满足您的需求。

答案 1 :(得分:0)

您需要执行从站点到企业的索引连接。见https://dzone.com/articles/join-faster-with-couchbase-index-joins

之后,使用GROUP BY和ARRAY_AGG()将站点收集到数组中。