Typeahead/Autocomplete

brikis98

Diamond Member
Jul 5, 2005
7,253
8
0
I'm looking around for an efficient algorithm for typehead/autocomplete on a website. That is, as you're typing into a text box, the page makes an AJAX call and displays a list of search terms that are similar to what you're typing. You see this a lot on travel websites where as you type the name of a departure/destination city/airport, all the choices that match your text pop up quickly. I have some decent ideas of how to do it using HashMaps but I'm sure there are standard solutions to this common problem. However, a quick google search didn't turn up anything too satisfying. The general problem requirements are:

* You have a dictionary of search terms
* Given some input string, you want to return 4-5 results from the dictionary that "match" the input string.
* The "match" can be simple, such as returning words from the dictionary that start with the input string, or more complicated, such as any words that contain the input string or even similar strings.

I'm just interested in seeing the different approaches to this problem so any/all algorithms you guys know of for this are appreciated.
 

Gunslinger08

Lifer
Nov 18, 2001
13,234
2
81
Seems fairly straightforward. Store your words in some filterable, cached collection (ex. in a .NET webapp, store them in an IEnumerable<SearchTerm> in the application Cache). Write a javascript function that makes a request back to the server onkeypress (ex. in .NET you can implement ICallBackEventHandler and make it a simple callback). On the server side, query your collection in the most efficient way you can think of (ex. in .NET, a LINQ query against an IEnumerable collection is O(n)) and respond to the client request with these values.
 

SJP0tato

Senior member
Aug 19, 2004
267
0
76
Just to throw my $0.02 in:

You can use plain Javascript and manually setup/call/maintain the Ajax connection. Or you can use a pre-defined Javascript framework like YahooUI, Dojo, or JQuery. These make things infinitely easier once you get them up and running if you have more to do than just the single auto-complete task.

I'm using Dojo extensively for work right now, but I've heard JQuery is supposedly the easiest to get up and running. I've heard good things about YahooUI as well.

Best of luck!