Ankit Bhardwaj
Ankit Bhardwaj

Reputation: 774

Sort documents on the basis of document property using cts:search

I have document properties for each document -

<prop:properties xmlns:prop="http://marklogic.com/xdmp/property">
  <prop:last-modified>2017-04-12T04:55:57Z</prop:last-modified>
</prop:properties>

Now I want to sort my search results using prop:last-modified. One way which I got to know is to use a loop. But this loop will have an impact on the performance of the query.

Is there any other way to get the search results with-in MarkLogic only?

Upvotes: 1

Views: 878

Answers (1)

Daniel Quinlan
Daniel Quinlan

Reputation: 2679

cts:search() allows an order-specification as one of its options, and you can use cts:index-order to set that option.

So if you're searching on prop:last-modified, it's not far to go from the example in the cts:search documentation. Unfortunately, this sorting option gets ignored (may be a bug).

cts:search(fn:doc(), "hello",
("unfiltered",
 cts:index-order(
     cts:element-reference(
         xs:QName("prop:last-modified")),
         "descending")))[1 to 10]

Note that you need an element range index defined for prop:last-modified.

Your workaround appears to be the most efficient and straightforward way to handle this. Pull the search results into a FLWOR statement, and sort them using plain old order by:

for $r in cts:search(fn:doc(), cts:true-query())
order by $r/property::prop:last-modified descending
return $r/property::prop:last-modified

Upvotes: 2

Related Questions