Search code examples
xquerymarklogic

Delete all documents matching a query?


I would like to delete all documents matching some predicates. The query I have come up with is as follows, but nothing is deleted from the database.

I suspect this is because the $doc is set to the XML value of the document rather than the document itself. Can anyone shed any light on this?

xquery version "1.0-ml";
for $doc in cts:search(fn:collection("MYCOLLECTIONNAME")/MyDocumentRoot,
    cts:or-query((
    cts:element-range-query (xs:QName("MyElement"), "=", "MyElementValue"),
    )), "unfiltered" )
    return xdmp:document-delete($doc);

The document looks like

<MyDocumentRoot>
  <MyElementName>MyElementValue</MyElementName>
</MyDocumentRoot>

Solution

  • You are indeed passing the contents of the documents into xdmp:document-delete instead of its uri. You could derive the uri using for instance fn:base-uri(), but like this all docs you want to delete are retrieved from the database first, which is unnecessary.

    Instead, enable the URI lexicon, and use cts:uris to do the deletion. It might also be wise to do the deletion in batches of lets say 1000 docs.

    HTH!