Search code examples
marklogicmarklogic-8

How to write cts query using marklogic java api


I want to run below query using the MarkLogic Java API

cts:search(fn:doc(), cts:and-query((cts:collection-query("/abc/xyz"), 
cts:collection-query("/abc/xyz/pqr"))))

Solution

  • Use a StructuredQueryBuilder, the and() and collection() methods to construct the equivalent structured query to search for documents that are in both the collections.

    // create the client -- this will change slightly in Java Client API 4.x
    DatabaseClient client = 
        DatabaseClientFactory.newClient(host, port, user, password, authType);
    // create a manager for searching
    QueryManager queryMgr = client.newQueryManager();
    
    // create a query builder
    StructuredQueryBuilder qb = new StructuredQueryBuilder();
    // build a search definition
    StructuredQueryDefinition query = 
        qb.and(
          qb.collection("/abc/xyz"), 
          qb.collection("/abc/xyz/pqr"));
    
    // run the search
    queryMgr.search(query, resultsHandle);