April 24, 2020
Estimated Post Reading Time ~

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 a 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.



  • Go to the SearchService.java interface and add the following method:
  • public String getResult();
  • In the SearchServiceImpl class, create a Resource Resolver. We have discussed this in length in the previous sessions. 
  • Map<String, Object> param = new HashMap<String, Object>(); param.put(ResourceResolverFactory.SUBSERVICE, "readService"); ResourceResolver resourceResolver=null; resourceResolver = resolverFactory.getServiceResourceResolver(param);
  • Create a session object using the adptTo method.
  • Session session = resourceResolver.adaptTo(Session.class);
  • Create a QueryManager object as follows:
  • javax.jcr.query.QueryManager queryManager = session.getWorkspace().getQueryManager();
  • 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')";
  • Create a JCR query.
  • javax.jcr.query.Query query = queryManager.createQuery(sqlStatement,"JCR-SQL2");
  • Obtain the result as follows:
  • javax.jcr.query.QueryResult result = query.execute();
  • Create a JCR node iterator and convert the result into an iterator.
  • javax.jcr.NodeIterator nodeIter = result.getNodes();
  • 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(); }
  • Return author.
  • Access the bundleservice component. Add the following code in the default script.<%= searchService.getResult()%>
  • Refresh the page we created. It should display the value of the author's property.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.