Full Text Search in AEM using Query Builder

07 / Jul / 2015 by Rachna Rajpal 2 comments

The full-text field search allows you to look for a field anywhere in a webpage, be it the title, content, or the url of a webpage.

A full-text search shall match whole words. For example, a full-text search on comments that contains “perform search” or “text search” or “text” will return a comment that contains “I want to perform text search in AEM”.

To implement the same in AEM6, I have used QueryBuilder API which is a service for building Queries for searching the Java Content Repository and are easily extensible.

Demostration with code:

Populate in a map all the predicates with the values.
Fulltext contains the value of the searchKey which will be searched in the url and the content of the cq:page, under the specified path

[java]

String pageTitle, pagePath
Map params = [:]
params["path"] = path
params["type"] = "cq:Page"
params["fulltext"] = searchKey
params["orderby"] = "@jcr:score"

[/java]

now use Query interface to create a query object that will in turn use builder object of Query Builder interface to build the query.

[java]

Query query = builder.createQuery(PredicateGroup.create(params), session)
//for pagination
query.setStart(startPage) // same as params["p.offset"] = startPage.toString()
query.setHitsPerPage(offset) // same as params["p.limit"] = offset.toString()

[/java]

searchResult will contain the result of the JCR query. A hit represents a single search result which is adapted to a page so as to fetch the page title and page url for display.

[java]
SearchResult searchResult = query.result
Long totalHits = searchResult.getTotalMatches()
for (Hit hit : searchResult.hits) {

Page page = hit.resource.adaptTo(Page)
pageTitle = page.title
pagePath = page.path
searchHit = new JSONObject()
searchHit.put("totalHits", totalHits)
searchHit.put("path", pagePath)

if (!pageTitle) {
pageTitle = pagePath.substring(pagePath.lastIndexOf(‘/’) + 1, pagePath.length())

}
searchHit.put("title", pageTitle)

resultArray.put(searchHit)
}
resultObject.put("data", resultArray)
return resultObject
[/java]

The desired output looks like below:
Search Result
This much should be sufficient to design a working Site Search component in AEM that performs fulltext Search and displays paginated results. I will introduce advanced fulltext queries in my forthcoming post.

Stay tuned!

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Veerendra

    Hi,I have just started working on AEM6.3, I need to call an API to power the search. Is there a complete doc to do that.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *