Apache
Home » Documentation » Bundles

Sling Query

SlingQuery is a Sling resource tree traversal tool inspired by the jQuery JavaScript API.

Introduction

The recommended way to find resources in the Sling repository is using tree-traversal methods, like listChildren() and getParent() rather than JCR queries. The latter are great for listing resources with given properties, but we can't leverage the repository tree structure with such queries. On the other hand, using tree-traversal method is quite verbose. Consider following code that takes an resource and returns its first ancestor, being cq:Page, with given jcr:content/cq:template attribute:

Resource resource = ...;
while ((resource = resource.getParent()) != null) {
    if (!resource.isResourceType("cq:Page")) {
        continue;
    }
    Resource template = resource.getChild("jcr:content/cq:template");
    if (template != null && "my/template".equals(template.adaptTo(String.class))) {
        break;
    }
}
if (resource != null) {
    // we've found appropriate ancestor
}

SlingQuery is a tool that helps creating such queries in a more concise way. Above code could be written as:

import static org.apache.sling.query.SlingQuery.$;
// ...
$(resource).closest("cq:Page[jcr:content/cq:template=my/template]")

Dollar sign is a static method that takes the resource array and creates SlingQuery object. The closest() method returns the first ancestor matching the selector string passed as the argument.

SlingQuery is inspired by the jQuery framework. jQuery is the source of method names, selector string syntax and the dollar sign method used as a collection constructor.

Features

Installation

Add following Maven dependency to your pom.xml:

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.query</artifactId>
    <version>3.0.0</version>
</dependency>

Documentation

External resources

Rev. 1809601 by tomekr on Mon, 25 Sep 2017 10:38:47 +0000
Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners.