HI @Rj113 ,
1. Use AEM QueryBuilder API to search for fulltext match
Map<String, String> queryMap = new HashMap<>();
queryMap.put("type", "cq:Page");
queryMap.put("fulltext", searchTerm); // e.g., "randomtext"
queryMap.put("p.limit", "-1");
Query query = queryBuilder.createQuery(PredicateGroup.create(queryMap), session);
SearchResult result = query.getResult();
2. Extract content from page properties (e.g., jcr:content/text) and highlight the search term
String getHighlightedSnippet(Node pageNode, String searchTerm) throws RepositoryException {
if (pageNode.hasNode("jcr:content") && pageNode.getNode("jcr:content").hasProperty("text")) {
String text = pageNode.getNode("jcr:content").getProperty("text").getString();
return extractSnippetWithHighlight(text, searchTerm);
}
return "";
}
3. Highlight the keyword using a snippet generator:
String extractSnippetWithHighlight(String content, String searchTerm) {
Pattern pattern = Pattern.compile("(.{0,50})(" + Pattern.quote(searchTerm) + ")(.{0,50})", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
return matcher.group(1) + "<span class='highlight'>" + matcher.group(2) + "</span>" + matcher.group(3) + "...";
}
return "";
}
Note:
This works with both AEM as a Cloud Service and on-prem AEM.
Make sure the text property exists and is plain text (not rich HTML).
You can extend this to parse cq:Page components that store text in nested nodes like responsivegrid.
Regards,
Amit