Querying: Suggestions

RavenDB has an indexing mechanism built upon the Lucene engine which has a great suggestions feature. This capability allows a significant improvement of search functionalities enhancing the overall user experience of the application.

Let's consider an example where the users have the option to look for products by their name. The index and query would appear as follows:

class Products_ByName extends AbstractIndexCreationTask {
    constructor() {
        super();

        this.map = `from product in docs.Products select new { 
            product.Name 
        }`;

        this.index("Name", "Search"); // (optional) splitting name into multiple tokens
        this.suggestion("Name"); // configuring suggestions
    }
}

const product = await session
    .query({ indexName: "Products/ByName" })
    .search("Name", "chaig")
    .firstOrNull();

If our database has Northwind samples deployed then it will not return any results. However, we can ask RavenDB for help:

const suggestionResult = await session
    .query({ indexName: "Products/ByName" })
    .suggestUsing(builder => builder.byField("name", "chaig"))
    .execute();

console.log("Did you mean?");

for (const suggestion of suggestionResult["name"].suggestions) {
    console.log("\t" + suggestion);
}
from index 'Products/ByName' 
select suggest('Name', 'chaig')

It will produce these suggestions:

Did you mean?
    chang
    chai

Client API

You can read more about suggestions in our Client API article.

Suggest Over Multiple Words

RavenDB allows you to perform a suggestion query over multiple words.

const resultsByMultipleWords = await session
    .query({ indexName: "Products/ByName" })
    .suggestUsing(builder =>
        builder.byField("name", [ "chaig", "tof" ])
               .withOptions({
                    accuracy: 0.4,
                    pageSize: 5,
                    distance: "JaroWinkler",
                    sortMode: "Popularity"
               }))
    .execute();

console.log("Did you mean?");

for (const suggestion of resultsByMultipleWords["name"].suggestions) {
    console.log("\t" + suggestion);
}

This will produce the following results:

Did you mean?
    chai
    chang
    chartreuse
    chef
    tofu

Remarks

Increased indexing time

Indexes with turned on suggestions tend to use a lot more CPU power than other indexes. This can impact indexing speed (querying is not impacted).