How to Implement Fuzzy Search (Google's Autocomplete Search) in Java
Join the DZone community and get the full member experience.Join For Free
Approximate String Search
Approximate String Search, Fuzzy Search, search with mistakes — there are many names for this one problem. In this article, I'll show you two ways to implement a search that takes potential misspelling into account.
Example of the Problem
A user types a company name with a mistake: Tetla, Aptle, Cola Koca, Mikrosoft, and the application returns the correct company name and similar companies (if any exist):
Spell Checker Algorithm Described by Google's Director of Research
Peter Norvig described an algorithm similar to Google's search spell checker in this article. I've changed the provided Java implementation according to the requirements set in this article. You can find the full source code here.
I've changed it a bit to fit our needs. In the dictionary, we add our four companies and after test it:
The algorithm is working as expected. For our inputs, we get the right correction: Tetla: tesla, Aktle: apple, CokaCola: cocacola, Mikrosaft: microsoft.
Unfortunately, this implementation doesn't support complex cases and therefore isn't ready for production. Let's take a look into the next, much more powerful solution.
Solr is an enterprise-search platform based on Apache Lucene. Solr has an embedded search that supports this misspelling feature. This project is a part of the Apache open source software foundation, so you can use it for free.
- Download and extract apache solr.
- Create new core:
solr create -c my_new_core
- Change solr\solr-8.4.1\server\solr\newcoretest\conf\solrconfig.xml. Find xml with DirectSolrSpellChecker and change value of field from _text_ to name.
Start Solr on the command line with:
solr start (execute administration mode). Then, create an empty Java project and http://www.apache.org/ with a Maven dependency:
After this step, the default spell check configuration will use the field, "name", in all documents.
Writing Search Application With Spelling Suggestions
Adding documents to
Requesting spelling suggestion request for word "coka":
For the requested word, "coka", the engine returns an existing word in our library (not documents):
suggestion for coka:coca
suggestion for coka:cola
Finally, searching for one of the matched suggestions: "coca"
Result of execution:
Matched document: Coca Cola
Solr Search Web Interface
For debugging purposes, you can use Solr's web interface. The default address is http://localhost:8983/ .
Spell check request example — searching for "coka" suggestions.
Searching for a specific company name that contains "coca":
The Solr configuration requires time to learn. It's painful at the very begging.
Alternative to Solr: Elasticsearch
Elasticsearch is a known alternative to Solr. It is more powerful but the full version is paid, and the free version has some limitations.
Opinions expressed by DZone contributors are their own.