Search code examples
marklogicmarklogic-9

How to write java script lookup functions in marklogic?


I have three json documents in my database with their unique URI's.

/employee/100.json

{
  "id": "100", 
  "name": "niranjan", 
  "status": "unprocessed"
}

/domain/100.json

{
  "id": "100", 
  "domain": "java"
}

/salary/100.json

{
  "id": "100", 
  "salary": "3000"
}

Now, I've to write a javascript lookup functions to fetch the details from corresponding documents based on "id" from /employee/100.json.

The output should look like this:

/final/100.json

{
  "id": "100", 
  "name": "niranjan", 
  "domain": "java",
  "salary": "3000"
}

How to do this??


Solution

  • One approach is to use a query similar to the following to retrieve the three documents:

    cts.search(cts.andQuery([
        cts.jsonPropertyValueQuery("id", "100"),
        cts.orQuery([
            cts.jsonPropertyScopeQuery("name",   cts.trueQuery()),
            cts.jsonPropertyScopeQuery("domain", cts.trueQuery()),
            cts.jsonPropertyScopeQuery("salary", cts.trueQuery())
            ])
        ]))
    

    The scope queries test the existence of properties. After retrieving the documents, your SJS code can create a JavaScript or JSON object with the merged properties.

    For more efficiency in a production application, you could create indexes on each of the documents using TDE and then join the documents using the Optic API.

    However ...

    Given that all three documents share the same key, the better approach is almost certainly to persist what you've identified as the output document and filter out any properties you don't need on retrieval.

    The DataHub Framework provides a guided way to stage documents and produce harmonized documents.

    Hoping that helps,