0

I am trying to count the occurrences of an XML structure in BaseX.

declare variable $a := 0;
for $node in db:open("My_DB")/my/xml//path
$a += 1

return $a

When running this, BaseX returns the error: Incomplete FLWOR expression: expecting 'return'.

I know that I can count with this simple function:

count(db:open("My_DB")/my/xml//path)

But there are two reasons zhy I am trying to do this with a for loop:

  1. I have been told by my supervisor that a for loop is faster
  2. In the future I may want to execute more operations per hit (in the for loop)

So the question is: how can I count elements in a for loop with XQuery using BaseX.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
  • Possible duplicate of [Updating counter in XQuery](http://stackoverflow.com/questions/10294677/updating-counter-in-xquery) – Jens Erat Feb 19 '16 at 11:01
  • Any statement that "X is faster than Y" not based on (and preferably accompanied by) measurements of concrete queries performed by concrete implementations is likely to be folklore. This particular claim is likely to tell you more about the source than about the speed of operations in BaseX or any other XQuery implementation. – C. M. Sperberg-McQueen Mar 02 '16 at 23:22

1 Answers1

1

As XQuery is a functional language, it’s not possible to reassign other values to a function. However, you can use fold-left to increment values in a loop:

fold-left(db:open("My_DB")/my/xml//path, 0, function($result, $curr) {
  $result + 1
})

The execution time for count() depends on the implementation of XQuery. In BaseX, count() is usually much faster than a loop, because it can in many cases be accelerated by lookups in the database statistics.

Christian Grün
  • 6,012
  • 18
  • 34