3
votes

Is there a way to join 2 documents within a marklogic database utilizing MarkLogic's Java API?

For instance let's say there's the following 2 documents:

doc1.xml:

<a>    
    <id>123</id>
    <doc2ID>111</doc2ID>
    <first_name>John</first_name>
</a>

doc2.xml:

<b>
    <id>111</id>
    <doc1ID>123</doc1ID>
    <last_name>Smith</last_name>
    <age>25</age>
</b>

Can i make the following query in MarkLogic: retrieve all records where first name = John, last_name = Smith and age > 20 ? In sql you would do something like this: Select a.first_name, b.last_name from doc1 a JOIN doc2 b ON (a.doc2ID = b.id) WHERE a.first_name = 'John' and b.last_name = 'Smith' and b.age > 24

2

2 Answers

2
votes

If you just want to use one document as a filter for another, you can send Query Options with a custom constraint that implements the subquery.

If you actually want to join documents, you would have to create a resource service extension that implements the join at the cts:search() level.

Stepping back, however, you should consider denormalizing your documents so you don't need to join as much as you would in a relational database. The documents you provide above are, in essence, table rows, which does not take advantage of the power and flexibility of a document database. Using relational models and relational queries is not the best approach in a document database.

0
votes

Your samples are not valid xml (no root element) and presumably there are more then one child elements. Without valid xml its hard to be precise in an answer.

The general way is you use a FLOWR expression:

for $master in doc("doc1.xml")//something,   
    $detail in doc("doc2.xml")//something 
where $master/doc2ID = $detail/id
return ($master/first_name/string(), $detail/last_name/string())