Search code examples
xquerymarklogic

How to minimize the use of FOR loop in XQuery?


I am having a code as Below and i want to know is it possible to get the same result without using FOR loop-

let $doc :=  cts:search(fn:doc(), 
                cts:element-value-query(......))

let $column-values := ("one,two,three....") (: Can be n number of values :)

let $tokenized-values := fn:tokenize($column-values, ",")

let $result := for $i in $doc
               let $temp := for $j in $tokenized-values
                              return fn:concat("$i//*:",$j)

                    return <root>{xdmp:value($temp)}</root>

return <result>{$result}</result>

Expected Result is as below-

<result>
  <root>
    <one>abc</one>
    <two>456</two>
    <three>675</three>
  </root>
  <root>
    <one>dfd</one>
    <two>235</two>
    <three>765</three>
  </root>
</result>

I am getting the results but how can i get the same result if i want to minimize the use of FOR loops.

Any Suggestions ?


Solution

  • To improve performance you could put a range index on all the columns you want to pull and use cts:element-value-tuples in lieu of cts:search . This would pull only the elements you want and not the whole document.

    For an alternate syntax of second for loop you could use this syntax :

    for $j in $tokenized-values
                              return fn:concat("$i//*:",$j)
    

    To

    $tokenized-values ! fn:concat("$i//*:", .)
    

    Although it's roughly the same in terms of performance.