Search code examples
node.jsmarklogicmarklogic-9

marklogic use node.js client api query doc with sub element


I use marklogic 9 with Node.js Client Api. when I try to use queryBuilder to search my doc, I find some problem.

this is my doc data

company: {
  uuid : uuid,
  name : comapnyName,
  parentCompany: {
    uuid: uuid,
    name: parentCompanyName,
  }
}

I want to find all the company below the parent company but not include parent company. I use

db.documents.query(
  this.qb.where(
    this.qb.directory('/company/'),
    this.qb.collection('company'),
    this.qb.word('name',parentCompanyName),
  )
).result();

this query find all the company include parent company. I think it find company.name and company.parentCompany.name.

How can I use BuilderQuery to find doc with company.parentCompany.name?


Solution

  • One approach is to specify a scope for the query:

    db.documents.query(
      qb.where(
        qb.directory('/company/'),
        qb.collection('company'),
        qb.scope('parentCompany', qb.word('name',parentCompanyName))
      )
    ).result();
    

    This query matches the name property anywhere under the parentCompany property. Such queries are equivalent to the cts.jsonPropertyScopeQuery() function in server-side JavaScript. For more information about the scope query builder function, see:

    http://docs.marklogic.com/jsdoc/queryBuilder.html#scope

    The path range index alternative specifies an explicit path instead of a scope relationship. If the scope relationship is not enough to eliminate false positives, that's the right way to go. As Wagner notes, the prerequisite is an additional index. The query would resemble the following:

    db.documents.query(
      qb.where(
        qb.directory('/company/'),
        qb.collection('company'),
        qb.word(qb.pathIndex('company/parentCompany/name'),parentCompanyName)
      )
    ).result();
    

    For more information about the pathIndex query builder function, see:

    http://docs.marklogic.com/jsdoc/queryBuilder.html#pathIndex

    Hoping that helps,