DZone
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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Build an MCP Server Using Go to Connect AI Agents With Databases
  • Segmentation Violation and How Rust Helps Overcome It
  1. DZone
  2. Coding
  3. Java
  4. How to Implement Fuzzy Search (Google's Autocomplete Search) in Java

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

By 
Dmitry Egorov user avatar
Dmitry Egorov
DZone Core CORE ·
Mar. 23, 20 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
28.5K 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.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!