XQuery/Limiting Result Sets

= Motivation = Sometimes you have many records or instances in a collection and you want to limit the amount of data returned by a query.

= Strategy =

Limiting Records in a Document
If you are limiting records in a large XML document you can do this by adding a predicate to the end of your for loop:

for $person in doc($file)/Person[position lt 10]

Using Subsequence to Limit Results
The following query retrieves only the first 10 documents, in sequential document order, contained within a collection.

for $person in subsequence(collection($my-collection)/person, 1, 10)

Where:

subsequence($sequence, $starting-item, $number-of-items)

Note that the second argument is the item to start at and the third is the total number of items to return. It is NOT the last item to return.

Sorting Before Limiting Results
Note that usually you will want to get the first N documents based on some sorting criteria, for example people that have a last name that start with the letter "A". So the first thing you must do is create a list of nodes that have the correct order and then get the first N records from that list. This can usually be done by creating a temporary sequence of sorted items as a separate FLWOR expression.

Getting the Next N Rows
After you fetch the first N items from your sequence you frequently want to get the next N rows. To do this you will need to add buttons to your report for "Previous N Records" and "Next N Records". Those buttons will pass parameters to your XQuery telling where to start and how many records to fetch.

To do this you will need to call your own script with different parameters on the URL. To keep track of the URL you can use the get-url function that comes with eXist. For example:

let $query-base := request:get-url

If your query was run from http:/localhost:8080/exist/rest/db/apps/user-manager/views/list-people.xq this is the string that would be returned.

We will also get two parameters from the URL for the record to start at and the number of records to fetch:

let $start := xs:integer(request:get-parameter("start", "1")) let $num := xs:integer(request:get-parameter("num", "20"))

Now we will create two HTML buttons that allow us to get next N records or the previous N records.

Full Example Program
 