return latest document based on a element in marklogic

血红的双手。 提交于 2019-12-24 12:12:12

问题


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())

Output

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

回答1:


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())

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.



来源:https://stackoverflow.com/questions/49677984/return-latest-document-based-on-a-element-in-marklogic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!