Creating a Google Suggest-Style Search


Published on January 9, 2005 at 12:21 PM EST
In the Tutorials category.

suggest.gif

Google Suggest offers suggestions while you’re typing in a search term. If you don’t know exactly what you’re looking for or how to spell it, the Suggest feature can make finding what you want easier. I’ve added the same functionality to danandsherree.com. Try it—start typing something in the search box at the right and watch the suggestions appear! It was a pretty easy feature to institute.

In an amazing piece of coincidence, Arvind at Movalog has just announced Suggest Search. For better or worse, his approach works a bit differently than mine.

If you want to use my incarnation of Suggest Search you’ll first need a list of suggested words. I used the <MTEntryTitle> field to generate all of my search terms, but any field(s) could be used easily enough. Create a new Index Template named search_suggestions.php with the following code in it:

<?php

// Collect all the words to build the suggestion list out of.
$string = strtolower( '<MTEntries lastn="10000"><MTEntryTitle remove_html="1" encode_php="q">
</MTEntries>' );

// Separate phrases (titles) into suggestion words.
$rawkeywords = preg_split('/\s*[\s+\.|\?|,|(|)|\-+|\'|\"|=|;|×|\$|\/|:|{|}]\s*/i', $string);

// Remove duplicates (including uc/lc).
$keywords = array_unique ( $rawkeywords );

// Sort them alphabettically.
sort( $keywords );

//Build the JavaScript array.
echo 'var customarray = new Array( ';

foreach ($keywords as $value) {
  echo "'$value', "; }

echo "'' );";

?>

To do the real work, I used the JavaScript AutoComplete code found at The Code Project. Download actb.js, then upload to your site.

Replace your existing search form with this one, being sure the file pathnames (bolded) correctly point to your site.

<script language="javascript" type="text/javascript" src="/actb.js"></script>
<script language="javascript" type="text/javascript" src="/search_suggestions.php"></script>
<form method="get" action="<$MTCGIPath$><$MTSearchScript$>">
<input type="hidden" name="IncludeBlogs" value="<$MTBlogID$>" />
<label for="search" accesskey="4">Search this site:</label><br />
<input id="search" name="search" size="20" onfocus="actb(this,event,customarray);" autocomplete="off" /><br />
<input type="submit" value="Search" />
</form>

If everything went well, you should have a Google Suggest-style Search box now!