title: xdmp:spawn-function() Alternative
body: <p>we have around &quot;20 million&quot; documents in the database and we have created badges of &quot;10000&quot; and use
  <strong>xdmp:spawn-function()</strong> to query over these 20 million documents and perform delete operations according to some conditions . But running it through query console, query is getting timeout .. Any alternate option we can look for so that the query doesn't get timed-out</p>
  <pre><code>xquery version &quot;1.0-ml&quot;;
  
  
  declare variable $versionToMaintain := 10;
  declare variable $batchSize := 10000;
  
  declare function local:delete($values) {
  
      for $value in $values
          let $versionToDelete :=  $value[3] - $versionToMaintain
      return 
          if ($versionToDelete &gt; 0) then 
              let $query := cts:and-query((
                  cts:collection-query('collection name 2'),
                  cts:element-range-query(xs:QName('version'), '&lt;=', xs:int($versionToDelete)),
                  cts:element-value-query(xs:QName('id'),$value[2]),
          cts:element-range-query(xs:QName('c:created-on'), '&lt;=', xs:dateTime(xdmp:parseDateTime('[Y0001]-[M01]-[D01]')
              ))
              return (cts:uris((), (), $query) ! xdmp:document-delete(.))
          else ()
  
  };
  
  let $totalDocs := 
      xdmp:estimate(
          cts:search(
              collection(&quot;collection name 1&quot;),
              cts:not-query(cts:element-value-query(xs:QName('version'), &quot;1&quot;)),
              &quot;unfiltered&quot;
          )
      )
  
  let $totalBatches := fn:ceiling($totalDocs div $batchSize)
  
  for $x in (1 to $totalBatches)
      let $values := 
          cts:value-tuples(
              (
                  cts:uri-reference(), 
                  cts:element-reference(xs:QName('id')), 
                  cts:element-reference(xs:QName('version'))
              ),
              (&quot;skip=&quot; || ($x - 1) * $batchSize, &quot;truncate=&quot; || $batchSize),
              cts:and-query((
                  cts:collection-query(&quot;collection name 1&quot;),
                  cts:not-query(cts:element-value-query(xs:QName('version'), &quot;1&quot;))
              ))
          )
      return 
      
              xdmp:spawn-function(function(){
              local:delete($values)
          })
  </code></pre>