DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > How to Implement Fuzzy Search (Google's Autocomplete Search) in Java

How to Implement Fuzzy Search (Google's Autocomplete Search) in Java

Dmitry Egorov user avatar by
Dmitry Egorov
CORE ·
Mar. 23, 20 · Java Zone · Tutorial
Like (7)
Save
Tweet
22.26K Views

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): 

User query with mistake Expected result
Tela Tesla
Apptle Apple
Cocakola CocaCola
Mikrosoft Microsoft

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:

Java
 




x
42


 
1
public class Spelling {
2
    private static final String ABC = "abcdefghijklmnopqrstuvwxyz";
3
    private static Map<String, Integer> dictionary = new HashMap<>();
4
    private static String DICTIONARY_VALUES = "Tesla,Apple,Microsoft,CocaCola";
5
    public static void main(String[] args) {
6
        Stream.of(DICTIONARY_VALUES.toLowerCase().split(",")).forEach((word) -> {
7
            dictionary.compute(word, (k, v) -> v == null ? 1 : v + 1);
8
        });
9
        System.out.println("Correction for Tela: " + correct("Tela"));
10
        System.out.println("Correction for Apptle: " + correct("Apptle"));
11
        System.out.println("Correction for Cocakola: " + correct("Cocakola"));
12
        System.out.println("Correction for Mikrosoft: " + correct("Mikrosoft"));
13
    }
14

          
15
    private static Stream<String> getStringStream(String word) {
16
        Stream<String> deletes = IntStream.range(0, word.length())
17
                .mapToObj((i) -> word.substring(0, i) + word.substring(i + 1));
18
        Stream<String> replaces = IntStream.range(0, word.length()).boxed().flatMap((i) -> ABC.chars()
19
                .mapToObj((c) -> word.substring(0, i) + (char) c + word.substring(i + 1)));
20
        Stream<String> inserts = IntStream.range(0, word.length() + 1).boxed().flatMap((i) -> ABC.chars()
21
                .mapToObj((c) -> word.substring(0, i) + (char) c + word.substring(i)));
22
        Stream<String> transposes = IntStream.range(0, word.length() - 1)
23
                .mapToObj((i) -> word.substring(0, i) + word.substring(i + 1, i + 2) + word.charAt(i) + word.substring(i + 2));
24
        return Stream.of(deletes, replaces, inserts, transposes).flatMap((x) -> x);
25
    }
26

          
27
    private static Stream<String> edits1(final String word) {
28
        return getStringStream(word);
29
    }
30

          
31
    private static String correct(String word) {
32
        Optional<String> e1 = known(edits1(word)).max(Comparator.comparingInt(a -> dictionary.get(a)));
33
        if (e1.isPresent()) return dictionary.containsKey(word) ? word : e1.get();
34
        Optional<String> e2 = known(edits1(word).map(Spelling::edits1).flatMap((x) -> x))
35
                .max(Comparator.comparingInt(a -> dictionary.get(a)));
36
        return (e2.orElse(word));
37
    }
38

          
39
    private static Stream<String> known(Stream<String> words) {
40
        return words.filter((word) -> dictionary.containsKey(word));
41
    }
42
}



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.

Apache Solr

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. 

Installation

  • 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.
XML
 




xxxxxxxxxx
1


 
1
<str name="field">name</str>
2
<str name="classname">solr.DirectSolrSpellChecker</str>



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:

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
  <groupId>org.apache.solr</groupId>
3
  <artifactId>solr-solrj</artifactId>
4
  <version>6.4.0</version>
5
</dependency>



After this step, the default spell check configuration will use the field, "name", in all documents. 

Writing Search Application With Spelling Suggestions

Initialization HttpSolrClient:

Java
 




xxxxxxxxxx
1


 
1
String urlString = "http://localhost:8983/solr/my_new_core";
2
HttpSolrClient solr = new HttpSolrClient.Builder(urlString).build();
3
solr.setParser(new XMLResponseParser());



Adding documents to my_new_core

Java
 




xxxxxxxxxx
1


 
1
Arrays.asList("Tesla", "Apple", "Microsoft", "Coca Cola").forEach(companyName -> {
2
  try {
3
    SolrInputDocument document = new SolrInputDocument();
4
    document.addField("name", companyName);
5
    solr.add(document);
6
    solr.commit();
7
  } catch (Exception ignored) {}
8
});



Requesting spelling suggestion request for word "coka":

Java
 




xxxxxxxxxx
1
13


 
1
SolrQuery params = new SolrQuery();
2
params.set("qt", "/spell");
3
params.set("q", "coka");
4
params.set("spellcheck", "on");
5
params.set("spellcheck.build", "true");
6

          
7
QueryResponse response = solr.query(params);
8
List<SpellCheckResponse.Suggestion> suggestions = response.getSpellCheckResponse().getSuggestions();
9
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
10
  for(String alternative: suggestion.getAlternatives()){
11
    System.out.println("suggestion for coka:" + alternative);
12
  }
13
}



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"

Java
 




xxxxxxxxxx
1
10


 
1
SolrQuery params = new SolrQuery();
2
params.set("qt", "/query");
3
params.set("q", "name:" + "coca");
4
params.set("spellcheck", "on");
5
params.set("spellcheck.build", "true");
6

          
7
QueryResponse response = solr.query(params);
8
for (SolrDocument document: response.getResults()){
9
  System.out.println("Matched document: " + document.getFieldValue("name"));
10
}



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.

Apache Solr web interface

Apache Solr web interface

Searching for a specific company name that contains "coca":

Searching for company name containing "coca"

Searching for company name containing "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. 

Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Anatomy of a Webhook HTTP Request
  • RestTemplate vs. WebClient
  • No-Code/Low-Code Use Cases in the Enterprise
  • Exhaustive JUNIT5 Testing with Combinations, Permutations, and Products

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo