Search code examples
xmlxpathxquerybasexflwor

how to include the value of position() in an Xquery result?


Without using tumbling windows, how is the position itself included in a result?

Obviously "$p" should be the "index" of each $item in $items. That being said, iteration isn't guaranteed to be sequential at all.

output:

<result>
  <items>
    <item pos="$p">5</item>
    <item pos="$p">3</item>
    <item pos="$p">7</item>
    <item pos="$p">2</item>
    <item pos="$p">7</item>
    <item pos="$p">3</item>
  </items>
</result>

query:

xquery version "3.1";

let $items := (5,3,7,2,7,3)
return
   <result>   
      <items>
      {
         for $item in $items[position()]
     let $p := position()
         return <item pos="$p">{$item}</item>
      }
      </items>
   </result>

query adapted from:

https://www.tutorialspoint.com/xquery/xquery_position.htm


Solution

  • You talk of using tumbling windows, but your query doesn't use tumbling windows.

    It does however use FLWOR expressions, and FLWOR expressions don't set the focus, which means they don't set the value of position().

    For your example, I think you want either

    for $item at $p in $items return <item pos="{$p}">{$item}</item>
    

    or more simply

    $items ! <item pos="{position()}">{.}</item>
    

    With tumbling windows you can bind variables to the positions of the start and end of the window by writing start at $s end at $e and then output $s and $e in your result.