Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build an autocomplete API?

I am trying to wrap my head around building a proper autocomplete functionality. I am practicing by building a really simple API that autocompletes users' names.

Currently, I have a database that contains columns, given_name and last_name. They are indexed with elasticsearch. And, I have built an API that accepts a search term to query elasticsearch.

I am concerned with how the frontend communicates with this API. The obvious way of doing it is to call the API after every keyup on the search input. However, this is a lot of requests being sent. Making calls after delays to reduce requests feels hacky. Is there an appropriate way of doing this?

I have found many guides on how to build an elasticsearch API but nothing that puts frontends and backends together.

like image 270
Marco Lau Avatar asked Dec 10 '15 03:12

Marco Lau


1 Answers

For sure, it is a lot of calls being issued! But for most applications, the number of suggestion options precludes client-based autocomplete.


However, an effective autocomplete feature should serve to reduce the number of (much more heavyweight) search requests being sent/rendered (while improving searcher experience) by reducing misspellings and zero-result searches among others.

Also Elasticsearch typically serves autocomplete requests fast (as in <10ms), freeing cluster resources significantly faster than search requests.


Common tweaks to reduce autocomplete-generated server traffic include:

  1. Imposing a minimum entry length (2-3 chars usually) before autocomplete is triggered.
  2. Adding a short delay after keyup (0.1-0.3s) before triggering so that fast/confident typists don't generate a burst of unnecessary/intermediate completion requests.
  3. Caching recent completion lists in browser so that <backspace> keystrokes don't trigger a server request.
  4. Pre-caching suggestions in browser (when feasible/bounded - e.g. Navigation, Friends/Contact names, etc... )

Twitter Typeahead.js incorporates all of the above API traffic optimizations for in-browser autocomplete. Take a look!

like image 110
Peter Dixon-Moses Avatar answered Nov 08 '22 16:11

Peter Dixon-Moses