You are probably looking for this:
Execute ad-hoc code on the server- with data mapped automatically to/from MarkLogic.
https://docs.marklogic.com/guide/java/resourceservices#id_47102
Take it for a test drive - looks like it suits your needs.
You also have the robust resource service extension options:
https://docs.marklogic.com/guide/java/resourceservices#id_27702
My absolute favourite is this:
https://docs.marklogic.com/guide/java/resourceservices#id_84134
Full module execution on MarkLogic with injected variables - with data mapped automatically to/from MarkLogic
We use this option as follows:
- We have a wrapper function in Java.
- It executes a main module in MarkLogic which is also a wrapper function
- The markLogic function is a fancy invoker for any other modules.
So, calling exec("a.b.c") on the java layer will actually execute function C in module B in directory A on the MarkLogic server -but the results are seamlessly available in the calling java code.
Its a bit more complex in real life(including security and per/post execution auditing), but certainly a pattern that can help you by keeping control over your xQuery/JS code and not allow injection of arbitrary code execution (because you execute only functions for which the connected user has rights to use).