I want a global variable which I can use in my different .xqy pages. Can I declare such a variable in xquery in Marklogic Server ?
4 Answers
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

- 858
- 3
- 12
- 24
-
1shouldn't that be $conf:PRECISION? – Tamas Apr 17 '18 at 08:58
-
1@Tamas, yes. Thank you. I've adjusted the example. – Andrei Orlov Mar 12 '19 at 20:40
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.

- 2,882
- 2
- 20
- 26
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.

- 11,681
- 1
- 24
- 39
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.