【问题标题】:N1QL query to join document, with the latest child (on basis of creationDateTime) in couchbaseN1QL 查询以加入文档,在 couchbase 中具有最新的子项(基于 creationDateTime)
【发布时间】:2019-10-13 20:18:59
【问题描述】:

N1QL 查询以获取 couchbase 中两个不同文档的连接结果中具有相同其他属性的最新文档

我有一个名为“价格”的存储桶,其中包含两种不同类型的文档“意图”和“请求”

  "intent"  (id = "intent1")
  {
  "locationDSL": "some_location"
  "product": "some_product1"
  }
  "intent"  (id = "intent2")
  {
  "locationDSL": "some_location2"
  "product": "some_product2"
  }
  "request"  (id = "request1")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-04-01",
  "status" : "success"
  }
  "request"  (id = "request2")
  {
  "intentId": "intent1",
  "createdDateTime": "2019-05-01"
   "status" : "failed"
  }
  "request"  (id = "request3")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-06-01",
 "status" : "failed"
  }
  "request"  (id = "request4")
  {
  "intentId": "intent2",
  "createdDateTime": "2019-07-01",
  "status" : "success"
  }

所以我有 2 个请求(“request1”和“request2”)用于“intent1”,2 个请求(“request3”和“request4”)用于 intent2,

我需要将“intent1”和“intent2”与最新请求(具有最新 createdDateTime 的请求)即“request2”和“ request4”,并且还可以过滤匹配“intentId”的最新子文档的某些字段,所以如果查询“status”=“success”,那么它应该只返回(intentId2,request4)而不是 (intent1,request1),因为在最新的孩子中,“request2”与条件不匹配

我可以加入文档,但加入的不是最新请求,而是所有匹配 intent.id 的请求。

这个问题类似于 [Filter documents using n1ql ,但我需要连接两个文档中的所有字段,而不是单个字段或属性

【问题讨论】:

  • JOIN 使用 ON 子句或 WHERE 子句使用您想要的字段。之后,您想生成最新的文档,使用基于 MAX 的聚合查询,如其他帖子所述。
  • 嗨 vsr,感谢您的回复,但是当我像链接中所示那样写时出现错误,
  • 选择意图,MAX([request.createdDateTime, request])[1] latestRequests FROM pricescmd request WHERE request.intentId IS NOT MISSING GROUP by request.intentId LETTING intents = (SELECT RAW intent.* FROM pricecmd 意图使用密钥 request.priceChangeIntentId)[0]; //pricescmd 是存储桶名称
  • code 4210:表达式必须是组键或聚合:
  • 嗨@vsr,我真的被困了很久,我有一个截止日期来完成,你能写下任务的完整查询吗......我将非常感谢你的帮助......我是 couchbase 和 n1ql 的新手

标签: join couchbase greatest-n-per-group n1ql


【解决方案1】:

根据您的查询尝试以下操作。子查询使用覆盖索引,只获取父查询中的最新文档

CREATE INDEX ix1 ON pricescmd(intentId, status, createdDateTime DESC);
SELECT intents, request
FROM (SELECT mx.*
      FROM pricescmd
      WHERE intentId IS NOT NULL 
      GROUP BY intentId, status
      mx = MAX([createdDateTime, {META().id, intentId, status} ])[1] )  AS d
LET request = (SELECT RAW request FROM pricescmd AS request USE KEYS d.id)[0],
    intents = (SELECT RAW intent FROM pricescmd AS intent USE KEYS d.intentId)[0];

【讨论】:

  • 嗨@vsr,谢谢你的回复,实际上我在从我的服务器复制粘贴时在上面的查询中混合了一些字段名称,priceChangeIntentId 实际上只是 intentId....
  • 使用更新的语句。如果您需要过滤掉,请在父查询中执行此操作
猜你喜欢
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多