What's the best way to implement AutoComplete in the server?
This question is easy people. Make a开发者_Go百科utocomplete beautiful in the client side of a web app is simple. There are a lot of plugins.
But, in the backside, in the server side, what's the best way to do it? I don't like the idea to hit the DB with each keypressed by the user.
I've been thinking about sphinx, or some full-text search engine running parallel from your site.
For example, if i have a PHP (high traffic) web site, i can create a parallel python script that get http requests from my "autocomplete textboxes". Then, when a user is pressing a key in the client side, the AJAX requests are directed to that python script that can use a special strategy.
What's your aproach?
Some conventions:
- Try not to hit the DB. I mean, get the request and do something SELECT * FROM foo WHERE bar LIKE "req%" is not a good answer. It may be a good strategy, but i know how to do it.*
- Replicated data can be a good choice.
I do agree that you need to have some better solution. Apache solr has a "suggestion" feature that you can use pretty well. If your data set is small then put all the data in memory and just do a simple loop.
On the front end, I recommend using setTimeout() to wait for about 200ms before firing the ajax call. If in that 200ms, another keystroke is triggered, then cancel the last timeout and start another one. This is a really clean solution where it wouldn't hit the db with each keystroke. I have used it in the past and it works really well.
This explains solr with jquery and how to create an autocomplete really well. http://www.mattweber.org/2009/05/02/solr-autosuggest-with-termscomponent-and-jquery/
You say in the comments that "It's a small dataset" of key words. Thus, it might be appropriate to have the client request the whole list as soon as the user starts typing into the field, then have the JavaScript respond to changes in user input on the client side.
That's one server hit per field per page (and only if the user types in the field), and you can cache it on the server so it rarely has to hit the DB.
Edit: Caching on the server is a big win because the list is the same for every request and for all users, but even better, this means you can cache the list in the client's browser by using an Expires
or Etag
header with a suitable period in the response. Thus the user can get unlimited autocompletion for just one (well-cached) server hit for the entire period of the browser cache.
精彩评论