Query for suggestions with index



Configure the index for suggestions

  • In order to be able to ask for suggested terms when querying an index field,
    that field must first be configured for suggestions in the index definition.

  • See the following sample index:
    (This index will be used in the examples ahead).

class Products_ByName extends AbstractJavaScriptIndexCreationTask {
    constructor() {
        super();
        
        this.map("Products", p => {
            return {
                ProductName: p.Name
            };
        });

        // Configure index-field 'ProductName' for suggestions
        this.suggestion("ProductName");

        // Optionally: set 'Search' on this field
        // This will split the field content into multiple terms allowing for a full-text search
        this.index("ProductName", "Search");
    }
}

Increased indexing time:

  • When configuring an index for suggestions, then during the indexing process,
    in addition to the regular breakdown of the data into terms (tokenization),
    RavenDB will scramble the terms to simulate common errors.

  • This can impact indexing speed but the cost of querying suggestions is Not impacted.

The index terms

Based on the Northwind sample data,
these are the terms generated for the above index Products/ByName:

Figure 1. Index terms

Terms generated for index Products/ByName

  1. The index-field name - as defined in the index definition.
    In this example the field name is ProductName.

  2. The terms that were generated for this index-field from the documents in the Products collection.

    • The image shows a partial view out of the 163 terms in this list.
    • The terms were generated by RavenDB's default search analyzer since full-text search was set on this field.

Suggest terms - for single term

Based on the Northwind sample data,
the following query on the index Products/ByName from above has no resulting documents,
since the term chokolade does Not exist in the index terms for index-field ProductName.

// This query on index 'Products/ByName' has NO resulting documents
const products = await session
    .query({ indexName: "Products/ByName" })
    .search("ProductName", "chokolade")
    .all();

If you suspect that the term chokolate in the query criteria is written incorrectly,
you can ask RavenDB to suggest similar terms from the index, as follows:

// Query the index for suggested terms for single term:
// ====================================================

const suggestions = await session
     // Query the index   
    .query({ indexName: "Products/ByName" })
     // Call 'suggestUsing'
    .suggestUsing(x => x
         // Request to get terms from index-field 'ProductName' that are similar to 'chokolade' 
        .byField("ProductName", "chokolade"))
    .execute();
// Query for terms from index-field 'ProductName' that are similar to 'chokolade'
from index "Products/ByName"
select suggest(ProductName, "chokolade")

// The resulting suggested terms:
// ==============================

console.log("Suggested terms in index-field 'ProductName' that are similar to 'chokolade':");
suggestions["ProductName"].suggestions.forEach(suggestedTerm => {
    console.log("\t" + suggestedTerm);
});

// Suggested terms in index-field 'ProductName' that are similar to 'chokolade':
//     schokolade
//     chocolade
//     chocolate

Suggest terms - for multiple terms

// Query the index for suggested terms for multiple terms:
// =======================================================

const suggestions = await session
     // Query the index   
    .query({ indexName: "Products/ByName" })
     // Call 'suggestUsing'
    .suggestUsing(x => x
         // Request to get terms from index-field 'ProductName' that are similar to 'chokolade' OR 'syrop'
        .byField("ProductName", ["chokolade", "syrop"]))
    .execute();
// Query for terms from index-field 'ProductName' that are similar to 'chokolade' OR 'syrop'
from index "Products/ByName" select suggest(ProductName, $p0)
{ "p0" : ["chokolade", "syrop"] }

// The resulting suggested terms:
// ==============================

// Suggested terms in index-field 'ProductName' that are similar to 'chokolade' OR to 'syrop':
//     schokolade
//     chocolade
//     chocolate
//     sirop
//     syrup

Suggest terms - for multiple fields

// Query the index for suggested terms in multiple fields:
// =======================================================

const suggestions = await session
     // Query the index   
    .query({ indexName: "Companies/ByNameAndByContactName" })
     // Call 'suggestUsing' to get suggestions for terms that are 
     // similar to 'chese' in first index-field (e.g. 'CompanyName') 
    .suggestUsing(x => x.byField("CompanyName", "chese"))
     // Call 'andSuggestUsing' to get suggestions for terms that are 
     // similar to 'frank' in an additional index-field (e.g. 'ContactName')
    .andSuggestUsing(x => x.byField("ContactName", "frank"))
    .execute();
class Companies_ByNameAndByContactName extends AbstractJavaScriptIndexCreationTask {
    constructor() {
        super();

        this.map("Companies", p => {
            return {
                CompanyName: p.Name,
                ContactName: p.Contact.Name
            };
        });

        // Configure the index-fields for suggestions
        this.suggestion("CompanyName");
        this.suggestion("ContactName");

        // Optionally: set 'Search' on the index-fields
        // This will split the fields' content into multiple terms allowing for a full-text search
        this.index("CompanyName", "Search");
        this.index("ContactName", "Search");
    }
}
// Query for suggested terms
// from index-field 'CompanyName' AND from index-field 'ContactName'
from index "Companies/ByNameAndByContactName"
select suggest(CompanyName, "chese"), suggest(ContactName, "frank")

// The resulting suggested terms:
// ==============================

// Suggested terms in index-field 'CompanyName' that is similar to 'chese':
//     cheese
//     chinese

// Suggested terms in index-field 'ContactName' that are similar to 'frank':
//     fran
//     franken

Suggest terms - customize options and display name

// Query the index for suggested terms - customize options and display name:
// =========================================================================

const suggestions = await session
     // Query the index   
    .query({ indexName: "Products/ByName" })
     // Call 'suggestUsing'
    .suggestUsing(x => x
        .byField("ProductName", "chokolade")
         // Customize suggestions options
        .withOptions({
            accuracy: 0.3,
            pageSize: 5,
            distance: "NGram",
            sortMode: "Popularity"
        })
        // Customize display name for results
        .withDisplayName("SomeCustomName"))
    .execute();
// Query for suggested terms - customize options and display name
from index "Products/ByName"
select suggest(
    ProductName,
    "chokolade",
    '{ "Accuracy" : 0.3, "PageSize" : 5, "Distance" : "NGram", "SortMode" : "Popularity" }'
) as "SomeCustomName"

// The resulting suggested terms:
// ==============================

console.log("Suggested terms:");
// Results are available under the custom name entry
suggestions["SomeCustomName"].suggestions.forEach(suggestedTerm => {
    console.log("\t" + suggestedTerm);
});

// Suggested terms:
//     chocolade
//     schokolade
//     chocolate
//     chowder
//     marmalade