MarkLogic: Sort your result dynamically in XQuery
To sort the result of an XQuery according to external parameters, nothing could be simpler, but you should have known that! Here is a little tip on the use of "order by", or more precisely on the sorting direction: "ascending" or "descending".
Let's take the following example of a sort on a modification date:
for $myDoc in xdmp:directory("/big-data/", "infinity")
order by $myDocxml@date-modification ascending
return $myDoc
order by $myDocxml@date-modification ascending
return $myDoc
Then I want to complete my query by making the direction of the sorting parameterisable. I immediately think of this syntax:
let $ordering := "ascending (: may come from an external parameter
return
for $myDoc in xdmp:directory("/big-data/ " , "infinity)
order by
for $myDoc in xdmp:directory("/big-data/ " , "infinity)
order by
if ($ordering = "ascending")
then ($myDocxml@date-modification ascending)
else ($myDocxml@date-modification descending)
return $myDoc
But BEWARE, this XQuery is false ! The error generated is: " Unexpected token syntax error".
As a result, we have to trick ourselves into adding sorting on "nothing" .... This has no effect on the performance of the query, but allows all use cases to be written:
let $ordering := "ascending (: may come from an external parameter
return
for $myDoc in xdmp:directory("/big-data/" , "infinity)
order by
if ($ordering = "ascending) then ($myDocxml@date-modification) else () ascending,
return
for $myDoc in xdmp:directory("/big-data/" , "infinity)
order by
if ($ordering = "ascending) then ($myDocxml@date-modification) else () ascending,
if ($ordering != "ascending") then ($myDocxml@date-modification) else () descending
return $myDoc
Simple, isn't it?
If you have any other tips, don't hesitate to react!
Are you interested in this topic?