Sunday 3 August 2014

Query Builder API

Query Builder API

Query Builder is an API to build queries which use JCR XPath underneath. Query Builder is exposed as
  1. Java API
  2. Rest API
 Java API QueryBuilder is available as an OSGi reference. This API can be used to build the queries using  predicate groups, example shown below.
  Map map = new HashMap();
 map.put("path", "/content");
 map.put("type", "nt:file");
 Query query = builder.createQuery(PredicateGroup.create(map), session);
 SearchResult result = query.getResult();

The REST API provides the same functionality through HTTP with response being rendered in JSON. HTTP Query request should start with the url http://localhost:4502/bin/querybuilder.json with all the search filters being provided as URL query parameters. Check out the examples below 

The search parameters provided above are path to search for and type of resource required .We have lot of parameters defined, some of them shown below
type = cq:Page         //  Type of resource
nodename = *.jar    //    Node name/pattern
orderby = @jcr:content/jcr:lastModified    // Order by property defined ( here its based on modified date)
orderby.sor t= desc  // ordering type

To search based on any property we can use 
property = jcr:content/cq:template    // Property name
property.value =apps/myapp/templates/mytemplate  //  Value of the property
To search multiple properties at a time
1.property = jcr:content/cq:template
1.property.value = apps/myapp/templates/mytemplate
2.property = jcr:content/jcr:title
2.property.value = MyTitle

To search for multi valued property - A property can have more than one value  (Array of values)
property = jcr:content/jcr:title
property.1_value = MyTitle1
property.2_value = MyTitle2
property.3_value = MyTitle3

Restricting the result (JSON Response)

By default QueryBuilder returns only default set of properties, If you want to have all the properties in your result use 
p.hits = full    

Most of the times we may be interested in only some selective properties, in that case we can specify the properties required separated by space 
p.hits = selective
p.properties = jcr:title sling:resourceType

By default we will only the first 10 hits, to get the entire search you can use
p.limit = -1
p.limit = 50 // only 50 hits will be retrieved

Query Debugger 

AEM provides Query Debugger which can be used to test, create and check the response time and results retrieved 

The debugger can be found at http://localhost:4502/libs/cq/search/content/querydebug.html
In the box provided you can put down all the query parameters as shown






Once you run this search query the result will be displayed as 







Result will have only 10 hits by default, its displays the time took for the search and the respective XPath query