How do I list all root directories and sub-directories in a MarkLogic database?

Viewed 484

MarkLogic allows organization of documents within a database using a pseudo "directory" like structure, defined by the URI used when any given document is loaded. These URIs are used to find and query documents (using fn:doc()), and to list all documents within a particular directory or subdirectory (using xdmp:directory()).

However, there doesn't appear to be any way to "view" or list all directories or subdirectories attached to documents within the database, as you would expect within a typical directory-structured filesystem. There are a few old solutions online and on SO that indicate ways to list root directories in the db, but none that allow for subdirectories, and none that work as simply as running a single piece of code to generate a full list of directories.

Is there any way to list all root and/or subdirectories within a database in MarkLogic?

1 Answers

There is actually a simple way to do this, using MarkLogic's URI lexicon, and some basic string-manipulation. (See https://docs.marklogic.com/cts:uris for more info).

To view all the sub-directories within a given directory in your MarkLogic database, simply run the below code in Query Console, with the $root-dir variable set to your desired parent directory. To find all directories within MarkLogic starting at the root, set $root-dir to "/".

This code lists all nested subdirectories recursively, showing full directory hierarchies starting at the root directory specified.

    (: List all subdirectories present within a ML root directory :)
    xquery version "1.0-ml";

    let $root-dir := "/directory/"

    let $uris := cts:uris((), (), cts:directory-query($root-dir, "infinity"))
    let $subdirs :=
      for $uri in $uris
      return fn:string-join(fn:tokenize(fn:replace($uri, $root-dir, "/"), "/")[1 to fn:last() - 1], "/") || "/"
    let $distinct-subdirs := fn:distinct-values($subdirs)
    return $distinct-subdirs

Thanks to mblakele for the initial code used here.

Related