根据marklogic中的元素返回最新文档 [英] return latest document based on a element in marklogic
问题描述
有一个包含4个文档的集合.我想检索带有最新时间戳的文档.
There is a collection with 4 documents. I want to retrieve the document with latest timestamp.
下面的查询有助于按降序排序,但是我要最新修改的文档
The below query helps to sort in descending order but I want the latest modified document
for $doc in fn:collection("/test")
order by $doc//timestamp descending
return $doc//id/text(),",",$doc//timestamp/text())
输出
1234, 2018-03-05T11:29:42.722Z
5678,2018-03-05T11:29:42.715Z
8976,2018-02-05T11:28:42.710Z
8976,2018-02-04T11:28:42.716Z
推荐答案
您的for循环已经生成了一个序列,因此您需要做的只是获取第一项.因此,您不必最终查询不需要的文档的值,只需将查询的输出呈现部分移到单独的表达式中即可.
Your for loop is already generating a sequence, so all you need to do is take the first item. And so you don't end up querying values for documents you don't want, move the output rendering portion of the query into a separate expression.
let $latest :=
(for $doc in fn:collection("/test")
order by $doc//timestamp descending
return $doc)[1]
return $latest//id/text(),",",$latest//timestamp/text())
现在,如果在 xs:dateTime
类型的 timestamp
上存在范围索引,则可以选择最新的文档,而无需先将所有这些文档加载到内存中并进行排序.但是,您可能必须将 $ doc//timestamp
替换为 $ doc/path/to/timestamp
(无双斜杠),查询优化器才能自动使用范围索引.
Now, if there is a range index on timestamp
of type xs:dateTime
, you can select the most recent document without first loading all those document into memory and sorting. However, you may have to replace $doc//timestamp
with $doc/path/to/timestamp
(no double-slash) for the query optimizer to automatically use a range index.
这篇关于根据marklogic中的元素返回最新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!