Using Query in CQ / AEM

You can use something like this

Assuming that you already know how to get repository session or resource resolver.

To get adminSession,

import javax.jcr.Session;

 @Reference

private SlingRepository repository;

adminSession = repository.loginAdministrative(null);


query = <Any Valid X path query>

final QueryManager qm = adminSession.getWorkspace().getQueryManager(); final Query q = qm.createQuery(query, Query.XPATH); final QueryResult result = q.execute(); final NodeIterator ni = result.getNodes();
--- Or (In JSP)
Iterator<Resource> iter = resourceResolver.findResources(query,"xpath");
-- Or brevity
Query q = adminSession.getWorkspace().getQueryManager().createQuery(query, Query.XPATH); Row r = q.execute().getRows().nextRow(); Value v = r.getValue("");


Using predicate Eval:


API


From HTTP request:

Session session = request.getResourceResolver().adaptTo(Session.class); PredicateGroup root = PredicateGroup.create(request.getParameterMap()); Query query = queryBuilder.createQuery(root, session); From hash map:
Map map = new HashMap(); map.put("path", "/content"); map.put("type", "nt:file"); Query query = builder.createQuery(PredicateGroup.create(map), session);
From predicates:
PredicateGroup group = new PredicateGroup(); group.add(new Predicate("mypath", "path").set("path", "/content")); group.add(new Predicate("mytype", "type").set("type", "nt:file")); Query query = builder.createQuery(group, session);

And then

SearchResult allLangMapResults = query.getResult();


Some Random Queries cheatsheet:

Xpath:



Check if a node has certain property but not other: //element(*,nt:unstructured) [jcr:like(@formPath, 'something%' ) and not(@something)]

Multiple order by in CQ / AEM:
1_orderby=@jcr:score
1_orderby.index=true
1_orderby.sort=desc
2_orderby=@post/pubDate
2_orderby.index=true
2_orderby.sort=desc

Or XPATH is
//element(*, cq:PageContent)
[Something]
order by @jcr:score descending, post/@pubDate descending

Search with node name CQ (Find all node under /content/geometrixx that has node name product
content/geometrixx//*[fn:name()='product']

Like Query in CQ / AEM:
path=/content type=cq:PageContent group.p.or=true group.0_property=fn:lower-case(post/@headingText) group.0_property.operation=like group.0_property.value=%talent connect%

Or XPATH is
/jcr:root/content//element(*, cq:PageContent) [ (jcr:like(fn:lower-case(post/@headingText), '%talent connect%')) ]








Comments