How to implement snippets, an enhancement to the display of search results

About Snippeting

To make it easier for users to read search results at a glance, add snippet functionality. When snippets are enabled, a brief portion of the document text is shown along with each search result.

Why Use Snippets?

Snippets can significantly increase the speed with which users can go from search to action, often providing enough information that the user does not even have to click on the search result link. For example, a list of results for local veterinarians might come with snippets that show each vet's phone number and address, making it easier and faster for the pet owner to quickly place a call to the nearest clinic.

Snippets can also help the user understand why a particular search is not returning the expected results. With this information, the user can refine the query.

Snippets are, in fact, so useful and so common that users probably take their presence for granted, and it is difficult to think of a reason for not using them.

How It Works

Snippets are selected by the Searchify server based on the search terms and snippet fields in the query.

  • Query: specify one or more document fields from which you want to pull snippets. It's fairly typical to use the text field. If you have defined custom document fields, you can use them as well.
  • Server: The Searchify server selects a portion of text to return as a snippet from each document field specified in the "snippet fields" clause of the query. The server selects the portion that contains as many as possible of the search terms from the query. For example, if the query is looking for the terms "vet" and "cat," a snippet that contians both those terms will be preferred over one that contains multiple instances of only one of the terms. The server returns up to 20 words of snippet text with the search terms highlighted.

Quick Start: Copy & Paste

Tweak the following code for your needs, and you're ready to go

Before you start

    • ruby
    • python
    • php
    • java

    For Ruby environments we provide a gem that handles all the REST calls for you in a very Ruby-fashioned way.

    • Download the Ruby client if you have not already done so.
    • Know your index's public URL. You'll need it to instantiate the client. Find the public URL on the Dashboard.

Set Snippet Fields in Query

The following code shows how to request snippets.

results = index.search(query, 
                       :fetch => 'title,timestamp', 
                       :snippet => 'text')

print results['matches'], " results\n"
results['results'].each {|doc|
    docid = doc['docid']
    title = doc['title']
    timestamp = doc['timestamp']
    text = doc['snippet_text']
    print "docid: #{docid}, title: #{title}, timestamp: #{timestamp}, text: #{text}" 
}

More Information