A Simple Guide to AEM Search APIs: Exploring Your Options for Powerful Search Functionality

As an AEM developer, the ability and skill to identify solutions and implementations to quickly and efficiently search through vast amounts of content is crucial. Understanding the all the AEM platform’s search API capabilities will ensure you are a effective developer, when implementing solutions for AEM search. In this article, we will explore the various options provided by AEM Search APIs, enabling you to make informed decisions while implementing search capabilities within your AEM projects. Throughout each search API topic, we will provide code examples as well, so you know exactly what to expect.


1. XPath Search API

XPath is a query language that allows you to navigate through the nodes and elements of an XML document. In the context of AEM, XPath queries can be used to search for content within the JCR (Java Content Repository) repository. While XPath is a powerful and flexible query language, it is essential to use it judiciously, as complex queries can have performance implications.

Some Benefits and Features:

  1. XPath Queries: XPath is a versatile query language that enables you to navigate through XML documents and locate specific nodes or elements within the content repository.
  2. Flexibility: XPath queries offer high flexibility and allow you to search content based on various criteria, making it suitable for complex search requirements.
  3. Node Structure: XPath queries rely on the hierarchical structure of nodes, making it well-suited for navigating and filtering content with a fixed structure.
  4. Rich Expressions: With XPath, you can employ a wide range of expressions, such as text matching, attribute filtering, and range-based searches.
    Dynamic Content: XPath can handle dynamic content, but developers should be cautious with complex queries as they may impact performance.

JAVA Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;

// Assuming you have access to the JCR Session object (session)
try {
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    String xpathQuery = "/jcr:root/content//*[@jcr:contains(., 'searchKeyword')]";
    Query query = queryManager.createQuery(xpathQuery, Query.XPATH);
    QueryResult result = query.execute();

    NodeIterator nodeIterator = result.getNodes();
    while (nodeIterator.hasNext()) {
        Node node = nodeIterator.nextNode();
        // Process the node that matches the search criteria
        System.out.println(node.getPath());
    }
} catch (Exception e) {
    // Handle exceptions
}

2. JCR SQL2 Search API

JCR SQL2 is a structured query language designed specifically for the Java Content Repository. It provides an SQL-like syntax for querying content stored in the repository. JCR SQL2 queries are generally more straightforward to use compared to XPath and are often preferred for basic search requirements due to their familiarity to developers familiar with SQL.

Some Benefits and Features:

  1. SQL-Like Syntax: JCR SQL2 provides a structured query language with an SQL-like syntax, making it more familiar to developers experienced in working with relational databases.
  2. Simplicity: JCR SQL2 queries are generally more straightforward to use compared to XPath, especially for developers already familiar with SQL.
  3. Dynamic Queries: JCR SQL2 supports dynamic queries, allowing you to parameterize search criteria and adapt to changing requirements.
  4. Performance Optimization: When used appropriately, JCR SQL2 can offer better performance for complex queries that involve multiple content nodes and properties.
  5. Full-Text Search: JCR SQL2 supports full-text search using the CONTAINS function, enabling text-based searches on content.

JAVA Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;

// Assuming you have access to the JCR Session object (session)
try {
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    String sql2Query = "SELECT * FROM [nt:unstructured] AS node WHERE CONTAINS(node.*, 'searchKeyword')";
    Query query = queryManager.createQuery(sql2Query, Query.JCR_SQL2);
    QueryResult result = query.execute();

    NodeIterator nodeIterator = result.getNodes();
    while (nodeIterator.hasNext()) {
        Node node = nodeIterator.nextNode();
        // Process the node that matches the search criteria
        System.out.println(node.getPath());
    }
} catch (Exception e) {
    // Handle exceptions
}

3. Query Builder Search API

The Query Builder API is a high-level API provided by AEM to build and execute queries against the repository. It acts as a wrapper around the underlying query languages (XPath or JCR SQL2) and provides a more intuitive and developer-friendly interface for constructing complex queries. The Query Builder API abstracts away the complexity of query languages and is recommended for most search scenarios in AEM.

Some Benefits and Features:

  1. High-Level API: The Query Builder API is a powerful and high-level abstraction for constructing and executing queries against the repository.
  2. Developer-Friendly: The Query Builder API provides a more intuitive interface compared to raw query languages, making it easier for developers to build complex queries.
  3. Abstraction of Complexity: The API abstracts away the underlying query language, making it more accessible to developers without extensive knowledge of XPath or JCR SQL2.
  4. Faceted Search: The Query Builder API supports faceted search, enabling users to filter search results based on predefined categories or facets.
  5. Spell Checker and Suggestions: The API includes built-in support for spell checking and real-time suggestions, improving the search experience for users.
  6. Great for Pagination: The Query Builder API offers built-in pagination support, allowing you to retrieve search results in manageable chunks. This is particularly useful when dealing with large result sets, as it enhances performance and reduces memory consumption.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import org.apache.sling.api.resource.ResourceResolver;

// Assuming you have access to the ResourceResolver object (resourceResolver)
try {
    QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
    String searchKeyword = "searchKeyword";
   
    // Building the predicate for the query
    PredicateGroup predicateGroup = PredicateGroup.create(
        "group.1_property", "jcr:content/@jcr:title",
        "group.1_property.operation", "fulltext",
        "group.1_property.value", searchKeyword
    );

    Query query = queryBuilder.createQuery(predicateGroup, resourceResolver.adaptTo(Session.class));
    com.day.cq.search.result.SearchResult result = query.getResult();

    for (com.day.cq.search.result.Hit hit : result.getHits()) {
        String path = hit.getPath();
        // Process the hit node that matches the search criteria
        System.out.println(path);
    }
} catch (Exception e) {
    // Handle exceptions
}

Hello, I am an enthusiastic Adobe Community Advisor and a seasoned Lead AEM Developer. I am currently serving as an AEM Technical Lead at MNPDigital.ca, bringing over a decade of extensive web engineering experience and more than eight years of practical AEM experience to the table. My goal is to give back to the AEM Full Stack Development community by sharing my wealth of knowledge with others. You can connect with me on LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back To Top