Home > front end >  Do I need to invoke JavaScript to construct a CTS query from JSON?
Do I need to invoke JavaScript to construct a CTS query from JSON?

Time:08-27

In MarkLogic, is there a way to construct a CTS query from a JSON serialization thereof in XQuery (without having to invoke JavaScript)? I only see a JSON example using JavaScript (and XML using XQuery) but not a JSON example using XQuery here: https://docs.marklogic.com/guide/search-dev/cts_query#id_17645

I successfully got the desired result when I ran the following code, but I would like to do this in just XQuery instead:

let $script := 'var json; cts.query(fn.head(xdmp.fromJsonString(json)))'
return
  xdmp:javascript-eval($script, map:entry("json", '{"wordQuery":{"text":["hello"], "options":["lang=en"]}}'))

Can it be done?

CodePudding user response:

  • xdmp:from-json-string() can be used to parse a JSON string. It will construct a JSON object (which is basically a specialized map).
  • You can convert that JSON object into a JSON document using xdmp:to-json().
  • select the child JSON object-node() from the returned document-object, and send to cts:query() to parse it into a cts:query

Like this:

xdmp:from-json-string('{"wordQuery":{"text":["hello"], "options":["lang=en"]}}') 
  ! xdmp:to-json(.)/object-node() 
  ! cts:query(.)
  • Related