How to Implement Search Components in AEM?
Search is one of the key features for any website. Implementing an efficient search component on a website can considerably improve the experience of visitors.
For AEM-powered sites, using Out-of-the-box (OOTB) search component without creating any new indexes has been a challenge. Our main goal here is to leverage OOTB search component and customize it to perform full-text search to enable users to search any word, number, or a sentence including the special characters in AEM website pages as well as DAM Assets. Search functionality shall be customized to different document types including Microsoft office documents and PDFs.
How to Implement Search Component in AEM?
Following are the 4 steps we consider implementing search component in AEM:
- We need to overlay the search component from core/wcm/components/search/v1/search
- Create custom search servlet which uses QueryBuilder API to do full-text search for pages and assets.
- Create search.html file under search component and make sure we call the custom search servlet.
- Refactor Oak Index definition for cqPageLucence (/oak:index/cqPageLucene) to search content tree depth level 4 and level 5.
Sample code
1. Servlet map
Map<String, String> predicatesMap = new HashMap<>(); predicatesMap.put(”fulltext”, fulltext); predicatesMap.put(“path”, searchRootPagePath); predicatesMap.put(“group.p.or”, “true”); predicatesMap.put(“group.1_group.path”, “/content”); predicatesMap.put(“group.1_group.type”, “cq:Page”); predicatesMap.put(“group.2_group.path”, “/content/dam”); predicatesMap.put(“group.2_group.type”, “dam:Asset”); PredicateGroup predicates = PredicateConverter.createPredicates(predicatesMap); ResourceResolver resourceResolver = request.getResource().getResourceResolver(); Query query = queryBuilder.createQuery(predicates, resourceResolver.adaptTo(Session.class));
2. Search html
<form class=”cmp-search__form” data-cmp-hook-search=”form” method=”get” action=”${currentPage.path @ addSelectors=[‘customsearchresults’], extension=’json’, suffix = search.relativePath}” autocomplete=”off”>
3. Refactor Page Lucene index
Output:
Through full-text search, we can improve the user experience on your AEM website. Additionally, the search component will help us in personalizing the site as we can incorporate analytics into this search to understand user requests on a more granular level.