Skip to content

Instantly share code, notes, and snippets.

@ableasdale
Created February 23, 2021 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ableasdale/1974f3803f35dfa6ffeb768acdba8405 to your computer and use it in GitHub Desktop.
Save ableasdale/1974f3803f35dfa6ffeb768acdba8405 to your computer and use it in GitHub Desktop.
MarkLogic: return a subset of the database as a downloadable zip file
xquery version "1.0-ml";
declare variable $TARGET-FILENAME as xs:string := "/tmp/"||xdmp:random()||".zip";
declare variable $URIS as xs:string* := cts:uris((), ("limit=100"));
declare function local:write-zipfile() {
let $zip := xdmp:zip-create(
<parts xmlns="xdmp:zip">{$URIS ! element part {.}}</parts>,
($URIS ! doc(.))
)
return xdmp:save($TARGET-FILENAME, $zip,
<options xmlns="xdmp:save">
<encoding>utf8</encoding>
</options>)
};
local:write-zipfile(),
xdmp:set-response-content-type("application/zip"),
xdmp:add-response-header("Content-Disposition", fn:concat("attachment; filename=", $TARGET-FILENAME)),
xdmp:external-binary($TARGET-FILENAME)
@ableasdale
Copy link
Author

Here's a second variation which skips the creation of the file in /tmp and instead builds the zip file in-memory and returns it:

xquery version "1.0-ml";

declare variable $TARGET-FILENAME as xs:string := "/tmp/"||xdmp:random()||".zip";
declare variable $URIS as xs:string* := cts:uris((), ("limit=100"));

declare function local:build-zipfile() {
  xdmp:zip-create(
    <parts xmlns="xdmp:zip">{$URIS ! element part {.}}</parts>,
    ($URIS ! doc(.))
  )
};

xdmp:set-response-content-type("application/zip"),
xdmp:add-response-header("Content-Disposition", fn:concat("attachment; filename=", $TARGET-FILENAME)),
local:build-zipfile()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment