0
votes

In MarkLogic how can I find a document URI where an element is

<sample-ref type="dated">

and value to match is 1742

Here is sample XML document:

<samples>
  <sample>
    <sample-ref type="dated">1742</sample-ref>
    <sample-ref type="undated">1742</sample-ref>
    <sample-xref type="sub">
      <sample-ref type="dated">TT 1742</sample-ref>
    </sample-xref>
    <sample-xref type="din">
      <sample-ref type="dated">
      </sample-ref>
    </sample-xref>
    <sample-xref type="sup">
      <sample-ref type="dated">XX 1742</sample-ref>
    </sample-xref>
  </sample>
</samples>

I only want to query this element where value matches 1742

<sample-ref type="dated">1742</sample-ref>

I have tried this query but it returns more then one uri:

cts.uris("", null, cts.elementValueQuery(xs.QName("sample-ref"), "1742", "exact"))

How can I refine this query

Thanks for your help

1

1 Answers

3
votes

You are trying to query for a document that contains a sample-ref element that has text content "1742" and a type attribute with value "dated". And maybe you've discovered that the following doesn't work:

cts.elementQuery(xs.QName('sample-ref'), cts.andQuery([
  cts.elementAttributeValueQuery(xs.QName('sample-ref'), xs.QName('type'), 'dated'),
  cts.elementValueQuery(xs.QName('sample-ref'), '1742')
]))

Because it turns out that, other than element-attribute queries, element queries within element queries only match descendants, not the descendants-or-self.

One solution to this problem is documented by David Cassel on his blog post here: http://blog.davidcassel.net/2012/08/a-trick-with-ctsnear-query/

By using cts.nearQueries with distance 0, it forces ML to find places where the sub-queries match the same element.

i.e.

cts.uris("", null, cts.nearQuery([
  cts.elementAttributeValueQuery(xs.QName('sample-ref'), xs.QName('type'), 'dated'),
  cts.elementValueQuery(xs.QName('sample-ref'), '1742')
], 0))

The blog post mentions that to make this run on the indexes, you will need to turn on two indexes on your database: element value positions and attribute value positions. Aside from the performance gains, if you're using the near-query within a cts.uris call, this is not optional - cts.uris will not 'filter' the results of the passed query, so without those indexes you will still get false positives.