Chapter 7. Document Searches
Finding documents is a core feature for searching in MarkLogic. Searches often begin with looking for simple words or phrases. Facets in the user interface, in the form of lists, graphs, or maps, allow users to drill into results. But MarkLogic’s Universal Index also captures the structure of documents.
The recipes in this chapter take advantage of the Universal Index to find documents with a specific root element and to look for documents that are missing some type of structure.
Search by Root Element
Problem
You want to look for documents that have a particular root XML element or JSON property and combine that with other search criteria.
Solution
Applies to MarkLogic versions 7 and higher
(: Return a query that finds documents with
: the specified root element :)
declare
function
local:query-root
(
$
qname
as
xs:QName
)
{
let
$
ns
:=
fn:namespace-uri-from-QName
(
$
qname
)
let
$
prefix
:=
if
(
$
ns
eq
""
)
then
""
else
"pre:"
return
xdmp:with-namespaces
(
map:new
(
map:entry
(
"qry"
,
"http://marklogic.com/cts/query"
)),
cts:term-query
(
xdmp:value
(
"xdmp:plan(/"
||
$
prefix
||
fn:local-name-from-QName
(
$
qname
)
||
")"
,
map:entry
(
"pre"
,
$
ns
)
)/
qry:final-plan
//
qry:term-query
/
qry:key
)
)
};
You can then call it like this:
declare
namespace
ml
=
"http://marklogic.com"
;
cts:search
(
fn:doc
(),
cts:and-query
((
local:query-root
(
xs:QName
(
"ml:base"
)),
cts:collection-query
(
"published"
)
))
)
Discussion
It’s easy to find all the documents that have a particular root element ...
Get MarkLogic Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.