Can I declare a global variable in xquery in Marklogic Server?

If your application is running on a single E-node, you can use server fields , which are sort of designed for this use case as well.


You have a few options. If you need a global constant variable, the config.xqy method mentions in @Andrew Orlov's answer is great because you avoid any locking from concurrent access to a properties.xml file.

If you need a variable that can be mutated across a cluster of nodes, the property.xqy example linked by @wst appears to use globally assigned namespaces to embed a retrievable key and value. Pretty clever. However, I'm not sure how much this is meant for heavy levels of change.

The E-node specific variable from @Eric Bloch is good, but please also be aware that it will not survive a system restart.

I'd be interested to know how these all compare performance-wise.


You can declare a variable in any module. For instance, it is config.xqy.

declare variable $PRECISION as xs:integer := 4;

For using this variable you need to import this module in your work module.

import module namespace config = "http://your-namespace" at "config.xqy";

And refer to this variable:

$config:PRECISION

If you need values accessible across the server, there is a library in the Marklogic XQuery Commons for storing persistent key/value pairs:

https://github.com/marklogic/commons/blob/master/properties/properties.xqy

And you may have already considered this, but you could also just simply store the global data in a document on the database and access with doc() - or eval() if you need to get to it from a different database.