N1QL查询以将最新的子项(基于creationDateTime)合并到Couchbase中以加入文档

时间:2019-05-28 10:14:45

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

N1QL查询以获取两个不同文档的合并结果的最新文档

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

  "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"
  }

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

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

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

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

1 个答案:

答案 0 :(得分: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];