Problem

You want to find all XML documents that are missing a particular element.

Solution

Applies to MarkLogic versions 7+

cts.search(
  cts.notQuery(
    cts.elementQuery(
      xs.QName("target"), 
      cts.trueQuery()
    )
  )
)
cts:search(
  fn:doc(),
  cts:not-query(
    cts:element-query(
      xs:QName("targetElement"), 
      cts:true-query()
    )
  )
)

For MarkLogic 7 and earlier, replace the cts:true-query()with cts:and-query(()).

Discussion

MarkLogic’s built-in search engine uses query criteria to identify matching fragments. The indexes map terms (words, phrases, structures, etc.) to fragment identifiers. To run a search, the specified terms are looked up in the appropriate index to find fragment identifiers. In the case of cts:not-query, the search will return any fragment identifiers except those matched by the nested query.

cts:element-query is a useful way to constrain a search to part of a document. The function restricts the nested query to matching within the specified XML element.

The query passed to cts:element-query is cts:true-query for MarkLogic 8 and above and cts:and-query(()) for MarkLogic 7 and before. cts:true-query does what it sounds like — it matches everything. Passed to cts:element-query, this provides a simple way to test for the existence of an element. If you’re using a version of MarkLogic that predates cts:true-query, the way to simulate it is to use cts:and-query and pass in the empty sequence to it. An and-query matches if all queries passed into are true; if none are passed in, then it matches, thus making cts:and-query(()) work the same as cts:true-query.

Learn More

Find documents that do NOT have a JSON Property

Learn how to find all JSON documents that are missing a particular property.

Application Developer's Guide

Read the guide that reviews over application development in MarkLogic Server.

MarkLogic Developer Track

Want to build that awesome app? Get off the ground quickly with the MarkLogic developer track.

This website uses cookies.

By continuing to use this website you are giving consent to cookies being used in accordance with the MarkLogic Privacy Statement.