0

I'm looking to get basic metadata about the data within a database. Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> open people
Database 'people' was opened in 225.24 ms.
> 
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
> 
> exit
See you.
thufir@dur:~/flwor/group$ 

Counting the lines:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex each.xq 
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$ 

code:

xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count
Thufir
  • 8,216
  • 28
  • 125
  • 273

2 Answers2

1

I suppose you simply want to use count(/text/line).

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • thanks, that'll work from Java I think, but I was hoping to also run from a FLWOR. I think it's the iteration over lines which causes the FLWOR to crash? I added an "answer" to elaborate. – Thufir Feb 17 '20 at 11:24
  • 1
    I don't see any reason to use a FLOWR but if so you obviously want `count(for ... return ...)`. – Martin Honnen Feb 17 '20 at 11:26
  • 1
    One of the biggest mistakes that XQuery beginners make (especially those coming from SQL) is to reach for FLWOR expressions as the solution to every problem. For the vast majority of queries, FLWOR expressions are overkill. – Michael Kay Feb 17 '20 at 11:38
0

From Martin's answer I see it's easy from within basex itself:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> open people
Database 'people' was opened in 208.33 ms.
> 
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 237.69 ms.
> 
> xquery count(/text/line)
13
Query executed in 20.55 ms.
> 
> exit
See you.
thufir@dur:~/flwor/group$ 

but I was also looking to run it from an xq file:

xquery version "3.0";

count(
for $line in db:open("people")
return $line/text/line)
Thufir
  • 8,216
  • 28
  • 125
  • 273