JPRLCol
JPRLCol

Reputation: 200

Filter records Marklogic using XQuery

I am trying to execute a query, but I am retrieving also records that I don't want to retrieve.

const rslt = cts.uris("", ["limit=500"],
    cts.andQuery(
    [
       cts.jsonPropertyValueQuery("language","java"),
       cts.collectionQuery("http://marklogic.com/collections/dls/latest-version"),
    ])
)
rslt

Based on the JSON:

{
   id: 1,
   language: [ 
      "java"
  ]
},
{
   id: 2,
   language: [ 
      "java", "C++"
  ]
}

I would like to retrieve the records with only java value, at the moment is retrieving 2 documents.

What conditional should I use to get only the document with language java, record 1 ?

Upvotes: 1

Views: 179

Answers (1)

Fiona Chen
Fiona Chen

Reputation: 1368

In MarkLogic, each JSON array value is a value of its associated property.

Given below input:

/stock/1.json
{
    "id": 1,
    "language": ["java"]
}

/stock/2.json
{
    "id": 2,
    "language": ["java", "C++"]
}

MarkLogic JavaScript:

const result = [];
const uris = cts.uris('', ['limit=500'],
      cts.andQuery([cts.collectionQuery('asset'),
                    cts.andNotQuery( 
                      cts.jsonPropertyValueQuery('language', 'java'),
                      cts.jsonPropertyValueQuery('language', 'C++'))
                   ])
                );
for (var uri of uris){
    result.push({'docId': uri})
}
result

or

const result = [];
const uris = cts.uris('', ['limit=500'],
      cts.andQuery([cts.collectionQuery('asset'),
                    cts.jsonPropertyValueQuery('language', 'java'),
                    cts.notQuery(cts.jsonPropertyValueQuery('language', 'C++'))
                   ])
                );
for (var uri of uris){
    result.push({'docId': uri})
}
result

Of course, above JavaScript has its XQuery equivalent.

Other than that, below MarkLogic XQuery would do:

for $doc in fn:collection("asset")
let $lang := $doc/language
where count($lang) = 1 and $lang/data() = "java"
return 
  <docId>
    {xdmp:node-uri($doc)}
  </docId>

Upvotes: 2

Related Questions