Search code examples
xquerymarklogic

XQuery function to use to connect and copy documents from one database to another in MarkLogic


What xquery functions I can use to connect with a MarkLogic database and copy the collection from that database to another database located in the same MarkLogic server.


Solution

  • You can use xdmp:invoke-function() and specify a different database in the options.

    xquery version "1.0-ml";
    for $doc in cts:search(doc(), cts:collection-query("collection-name"))
    let $uri := $doc/base-uri()
    let $collections := xdmp:document-get-permissions($uri)
    let $permissions := xdmp:document-get-collections($uri)
    return
      xdmp:invoke-function(function() { 
          xdmp:document-insert($uri, $doc, $permissions, $collections) 
        },
        <options xmlns="xdmp:eval">
          <database>{ xdmp:database("GTM2_TEST") }</database>
        </options>)
    

    If you have a really large number of documents in the collection, then you might want to look at either xdmp:spawn-function(), or doing the work with a batch tool, such as CoRB to avoid Expanded Tree Cache errors and/or timeouts from an attempt to process them all in one giant transaction.