从多个 collection 中搜索最新文档

search latest document from multiple collection

有2个collection/test/123和test/567我要return最新的 collections.

的文档
let $a := cts:collection-match("/test/*")
 for $t in $ a
 let $latest :=(
 for $doc in fn:collection( $t)
  order by $doc//timestamp descending 
  return $doc)[1]
 return fn:concat($latest//id/text(),",",$latest//timestamp/text())

预计

4567,2018-04-05T11:28:47.722Z 1234, 2018-04-05T11:28:47.040Z

我认为 @wst 在您之前的问题中仅谈论一个集合(参见 )的答案也可以适用于多个集合。这主要是括号放置不同的问题。此外,fn:collection 也接受一个序列,因此适应早期的解决方案几乎是微不足道的:

let $latest :=(
  for $doc in fn:collection(
    cts:collection-match("/test/*")
  )
  order by $doc//timestamp descending 
  return $doc
)[1]
return fn:concat($latest//id/text(),",",$latest//timestamp/text())

<update>

Re-reading 问题(添加的预期部分有所帮助,谢谢),我发现我可能误解了所需的输出。您不是在所有匹配集合中查找最新结果,而是希望每个集合中的最新结果按降序显示。这看起来略有不同,而且你离得并不远。您只需要第二个 order by 子句:

let $a := cts:collection-match("/test/*")
for $t in $a
let $latest := (
  for $doc in fn:collection($t)
  order by $doc//timestamp descending 
  return $doc
)[1]
order by $latest//timestamp descending
return fn:concat($latest//id/text(),",",$latest//timestamp/text())

话虽如此,使用 MarkLogic 可能会有更高效的方法来执行此操作。如果你的时间戳上有一个日期时间范围索引,你可以允许 MarkLogic 使用它来快速找到升序或降序中的第一个。最清晰的方法是使用 cts:search with a cts:index-order 参数。类似于:

let $a := cts:collection-match("/test/*")
for $t in $a
let $latest := cts:search(
  collection(),
  cts:collection-query($t),
  cts:index-order(
    cts:element-reference(
      fn:QName("","timestamp"),
      "type=dateTime"
    ),
    "descending"
  )
)[1]
order by $latest//timestamp descending
return fn:concat($latest//id/text(),",",$latest//timestamp/text())

</update>

HTH!