Expand my Community achievements bar.

Adobe Summit 2025: AEM Session Recordings Are Live! Missed a session or want to revisit your favorites? Watch the latest recordings now.

How to populate search results content, with search term/text highlighted in it?

Avatar

Level 1

We have a scenario, when a user searches with a term and AEM pulls in the pages that that term lives on, the term itself would appear in the page of search results with highlighted design.

For example, if I search for “randomtext”, these are the results that I get. Entry points into “randomtext” is on both pages but the term itself isn’t surfaced with OOTB query results, which leaves the user wondering which page actually contains the information they are looking for.

  • Would it be possible to allow search results to pull something from the page that contains the keyword that was searched? 

  • What other options might be possible to accomplish the goal of having the keyword surfaced on the search results page?

Any idea on this? TIA.

2 Replies

Avatar

Community Advisor

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:

Avatar

Community Advisor

@Rj113 Did you find the suggestions helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you've discovered a solution yourself, we would appreciate it if you could share it with the community. Thank you!


Aanchal Sikka