Archive for July, 2016

Search in AEM repository

In the last session, we have seen how to add a property to a JCR node. We primarily created a resourceResolver object and created a resource using the path to the node where we wanted to set the property. Converted the resource into a Node using the adptTo() method. And, then used the setProperty() method to set the property. Finally, we created a session object in the similar manner, and then saved the property.

In this session, we will see how to perform a basic search option. There are many ways to accomplish the same. We will see the simplest way. The intention is to be cognizant of how a search operation is performed. In the repository, we will search for the page that contains a property author which is set to Sunil.

  1. Go to the SearchService.java interface and add the following method:
    public String getResult();
  2. In the SearchServiceImpl class, create a Resource Resolver. We have discussed this in length in of the previous sessions.
    Map<String, Object> param = new HashMap<String, Object>(); 
    param.put(ResourceResolverFactory.SUBSERVICE, "readService");
    ResourceResolver resourceResolver=null;
    resourceResolver = resolverFactory.getServiceResourceResolver(param);
  3. Create a session object using the adptTo method.
    Session session = resourceResolver.adaptTo(Session.class);
  4. Create a QueryManager object as follows:
    javax.jcr.query.QueryManager queryManager = session.getWorkspace().getQueryManager();
  5. Create a query String.
    We need to find the page that contains author property as Sunil.

    String sqlStatement = "SELECT * FROM [cq:PageContent] WHERE CONTAINS(author, 'Sunil')";
  6. Create a JCR query.
    javax.jcr.query.Query query = queryManager.createQuery(sqlStatement,"JCR-SQL2");
  7. Obtain the result as follows:
    javax.jcr.query.QueryResult result = query.execute();
  8. Create a JCR node iterator and convert the result into an iterator.
    javax.jcr.NodeIterator nodeIter = result.getNodes();
  9. Use the following code to find the node and get its properties, such as author and title.
    while ( nodeIter.hasNext() ) {
     LOGGER.info("From the search");
     javax.jcr.Node node = nodeIter.nextNode();
     title = node.getProperty("jcr:title").getString();
     author = node.getProperty("author").getString();
     }
  10. Return author.
  11. Access the bundleservice component. Add the following code in the default script.
    <%= searchService.getResult()%>
  12. Refresh the page we created. It should display the value of the author property.