Autocomplete & Spellcheck Implementation

Documentation > WEB CRAWLER-Solr API > Autocomplete & Spellcheck Implementation

Autocomplete & Spellcheck Implementation

Two features that make any search experience feel professional: autocomplete (typeahead suggestions as the user types) and spellcheck ("Did you mean...?" when the user misspells a word).

Both are built into your Opensolr Web Crawler index and ready to use.


Autocomplete (Typeahead Suggestions)

Your index has a dedicated /autocomplete endpoint that returns suggestions based on edge n-gram indexed fields. As the user types each character, you send a request and display matching suggestions instantly.

How to Query Autocomplete

/autocomplete?q=ope&rows=5&wt=json&fl=title,uri&qf=title_tags_ws+tags_ws+title_tags+tags&defType=edismax
Parameter Value Description
q User's partial input (e.g., ope) What the user has typed so far
rows 5 or 10 How many suggestions to show
fl title,uri Fields to return (you just need the title and URL)
qf title_tags_ws tags_ws title_tags tags The edge n-gram fields to search
defType edismax Use the eDisMax query parser
wt json JSON response format

Autocomplete Fields Explained

There are four autocomplete fields, each behaving slightly differently:

Field Tokenizer Behavior
title_tags Keyword (whole field) Matches the title as one complete phrase prefix
tags Keyword (whole field) Matches the full tag/URL as one prefix
title_tags_ws Whitespace (per word) Matches individual words in the title
tags_ws Whitespace (per word) Matches individual words in tags/URLs

Using all four in qf gives you the best mix: the user gets suggestions whether they are typing the beginning of a page title or a word that appears in the middle.

JavaScript Implementation

var debounceTimer;
var searchInput = document.getElementById("searchInput");
var suggestionsDiv = document.getElementById("suggestions");

searchInput.addEventListener("input", function() {
    clearTimeout(debounceTimer);
    var query = this.value.trim();

    if (query.length < 2) {
        suggestionsDiv.innerHTML = "";
        return;
    }

    // Debounce: wait 150ms after the user stops typing
    debounceTimer = setTimeout(function() {
        var acUrl = SOLR_URL.replace("/select", "/autocomplete")
            + "?q=" + encodeURIComponent(query)
            + "&rows=7&wt=json&fl=title,uri"
            + "&qf=title_tags_ws+tags_ws+title_tags+tags"
            + "&defType=edismax";

        fetch(acUrl, {
            headers: { "Authorization": "Basic " + btoa(SOLR_USER + ":" + SOLR_PASS) }
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var docs = data.response.docs;
            if (docs.length === 0) {
                suggestionsDiv.innerHTML = "";
                return;
            }
            var html = "<ul class="autocomplete-list">";
            docs.forEach(function(doc) {
                html += "<li><a href="" + doc.uri + "">" + doc.title + "</a></li>";
            });
            html += "</ul>";
            suggestionsDiv.innerHTML = html;
        });
    }, 150);
});

Styling the Autocomplete Dropdown

.autocomplete-list {
    list-style: none;
    margin: 0;
    padding: 0;
    border: 1px solid #ddd;
    border-radius: 0 0 6px 6px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    max-height: 300px;
    overflow-y: auto;
}
.autocomplete-list li a {
    display: block;
    padding: 10px 14px;
    text-decoration: none;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
}
.autocomplete-list li a:hover {
    background: #f5f5f5;
}

Tips

  • Debounce the requests — do not send a request on every single keystroke. 100-200ms delay is good.
  • Minimum 2 characters before sending autocomplete requests — single character queries return too many results.
  • Hide the dropdown when the input is empty or when the user presses Escape.
  • Keyboard navigation — let users use arrow keys to navigate suggestions and Enter to select.

Spellcheck ("Did You Mean...?")

Spellcheck is handled by the /select endpoint itself. Add spellcheck parameters to your regular search query:

spellcheck=true
spellcheck.q=your search terms
spellcheck.count=5
spellcheck.collate=true
spellcheck.maxCollationTries=15
spellcheck.maxCollations=3

How Spellcheck Works

  1. The user searches for "opnesolr ducumentation"
  2. Solr's spellchecker compares each word against the dictionary built from your indexed content
  3. It finds that "opnesolr" is likely "opensolr" and "ducumentation" is likely "documentation"
  4. The collation feature combines the corrections into a complete corrected query: "opensolr documentation"

Parsing the Spellcheck Response

function getSpellcheckSuggestion(data) {
    if (!data.spellcheck || !data.spellcheck.collations) return null;

    var collations = data.spellcheck.collations;
    // Collations array: ["collation", "corrected query", "collation", "another correction", ...]
    for (var i = 0; i < collations.length; i++) {
        if (collations[i] === "collation" && collations[i + 1]) {
            return collations[i + 1];
        }
    }
    return null;
}

// Usage:
var suggestion = getSpellcheckSuggestion(data);
if (suggestion && data.response.numFound < 3) {
    // Show a "Did you mean" link that re-runs the search
    var link = document.createElement("a");
    link.href = "#";
    link.textContent = suggestion;
    link.onclick = function(e) {
        e.preventDefault();
        document.getElementById("q").value = suggestion;
        doSearch();
    };
    var p = document.createElement("p");
    p.className = "spellcheck";
    p.textContent = "Did you mean: ";
    p.appendChild(link);
    p.appendChild(document.createTextNode("?"));
    resultsDiv.prepend(p);
}

When to Show Suggestions

A good rule of thumb: show the "Did you mean...?" suggestion when:

  • The spellcheck response contains a collation, AND
  • The original query returned few or no results (e.g., numFound < 5)

Do not show it when the query already returns plenty of results — the user probably spelled things correctly even if Solr has an alternative suggestion.