I want to create a counter in xquery. My initial attempt looked like the following:
let $count := 0
for $prod in $collection
let $count := $count + 1
return
<counter>{$count }</counter>
Expected result:
<counter>1</counter>
<counter>2</counter>
<counter>3</counter>
Actual result:
<counter>1</counter>
<counter>1</counter>
<counter>1</counter>
The $count
variable either failing to update or being reset. Why can't I reassign an existing variable? What would be a better way to get the desired result?
All the solution above are valid but I would like to mention that you can use the XQuery Scripting extension to set variable values:
You can try this example live at http://www.zorba-xquery.com/html/demo#twh+3sJfRpHhZR8pHhOdsmqOTvQ=
Immutable variables
XQuery is a functional programming language, which involves amongst others immutable variables, so you cannot change the value of a variable. On the other hand, a powerful collection of functions is available to you, which solves lots of daily programming problems.
let $count
in line 1 defines this variable in all scope, which are all following lines in this case.let $count
in line 3 defines a new$count
which is0+1
, valid in all following lines within this code block - which isn't defined. So you indeed increment$count
three times by one, but discard the result immediatly.BaseX' query info shows the optimized version of this query which is
The solution
To get the total number of elements in
$collection
, you can just useFor a list of XQuery functions, you could have a look at the XQuery part of functx which contains both a list of XQuery functions and also some other helpful functions which can be included as a module.
I think you are looking for something like:
XQUERY:
OUTPUT:
Try using 'at':
This will give you the position of each '$d'. If you want to use this together with the
order by
clause, this won't work since the position is based on the initial order, not on the sort result. To overcome this, just save the sorted result of the FLWOR expression in a variable, and use theat
clause in a second FLWOR that just iterates over the first, sorted result.Specific to MarkLogic you can also use
xdmp:set
. But this breaks functional language assumptions, so use it conservatively.http://docs.marklogic.com/5.0doc/docapp.xqy#display.xqy?fname=http://pubs/5.0doc/apidoc/ExsltBuiltins.xml&category=Extension&function=xdmp:set
For an example of
xdmp:set
in real-world code, the search parser https://github.com/mblakele/xqysp/blob/master/src/xqysp.xqy might be helpful.As @Ranon said, all XQuery values are immutable, so you can't update a variable. But if you you really need an updateable number (shouldn't be too often), you can use recursion:
This behaves exactly as you intended with your example.
In XQuery 3.0 a more general version of this function is even defined in the standard library: fn:fold-right($f, $zero, $seq)
That said, in your example you should definitely use
at $count
as shown by @tohuwawohu.