Match Highlighting for Search in CrafterCMS

Highlighting search terms in search results is a common requirement for many websites.  CrafterCMS builds on top of Apache Solr and make implementing rich search and other query-driven experiences super simple.

In this tutorial, we’ll create a simple article search backend that highlights the search terms that were used within the results returned to the user.

Step 0: Prerequisites

If you haven’t gotten CrafterCMS set up and built your first site you can follow this tutorial to get started: Working with Your First CrafterCMS Web site.

Step 1: Build a content model for articles

The next thing we need is content to query against.  The first step in supporting content creation is defining the Content Type.  The Content type is the definition of the structure of a particular type of content.  In our example, we want to define the structure of an Article.

A simple article should have:

  • A Url
  • A title
  • An author name
  • A body

To define this we use Crafter’s Content Type management console:  Below you can see the example model including the fields and their types.


You can learn more about content modeling here Content Modeling in CrafterCMS.

Step 2: Create content

Now that you have your article content type defined you can create articles.  To create an article open the pages folder (we modeled the article as a page with a URL) in the sidebar and right click on the home page:


Step 3: Create a REST script to return highlighted results

Now that you have content you can write a RESTful controller and test it.  Let’s create a simple GET based REST controller.

  1. Open the Sidebar and locate the Scripts folder.
  2. Open the Scripts folder and navigate to “rest” folder.
  3. Right click on it and choose “Create Controler

  4. In the script name dialog, enter “search.get” and click Create.
  5. Enter the following code:
// build a query
def keyword = params.q 
def queryStatement = "content-type:\"/page/article\" " 
 
 if(keyword) {
      queryStatement += " AND $keyword"
 }
 
 def query = searchService.createQuery()
 query.setQuery(queryStatement)
 query.addParam("hl", "true")
 query.addParam("hl.fl", "body_html")
 query.addParam("hl.simple.pre", "<b>")
 query.addParam("hl.simple.post", "</b>")
 
 // execute the query
 def executedQuery = searchService.search(query)

def matches = [:]
matches.found = executedQuery.response.numFound
matches.articles = executedQuery.response.documents
matches.highlights = executedQuery.highlighting

return matches

Step 4: Execute the Script

In a browser, go to http://SERVER:PORT/api/search.json?q=AWORDTHATEXISTSINRESULTS

example: http://localhost:8080/api/search.json?q=bacon