Building a search interface for local indexes in MVC

To perform searches based on locally stored search indexes on MVC sites, use the API from the CMS.Search namespace (provided as part of the Kentico.Libraries NuGet package).

  1. Prepare a SearchParameters object with the required search inputs and parameters.
  2. Call the SearchHelper.Search method.

    Example
                IEnumerable<string> searchIndexes = new List<string> { "ProductIndex", "ArticleIndex" };
                int pageNumber = 1;
                int pageSize = 10;
                UserInfo searchUser = MembershipContext.AuthenticatedUser;
                string cultureCode = "en-us";
                bool combineWithDefaultCulture = true;
     
                SearchParameters searchParameters = SearchParameters.PrepareForPages("search query", searchIndexes, pageNumber, pageSize, searchUser, cultureCode, combineWithDefaultCulture);
     
                SearchResult searchResult = SearchHelper.Search(searchParameters);
    


The Search method returns a SearchResult object representing the set of results. The result's Items property contains a collection of SearchResultItem objects, representing individual search results.

Every item provides properties corresponding to general search result fields (such as the title, image or content fields), as well as a Data property. The Data property is of an abstract BaseInfo type, and its run-time type depends on the searched Kentico object. For example:

  • If the search indexes pages, the run-time type of a search result item's Data property is of the TreeNode class. If you generated classes for your page types, the run-time type is of the generated class.
  • If the search indexes pages representing products, the run-time type of a search result item's Data property is of the SKUTreeNode class.
  • If the search indexes users, the run-time type of a search result item's Data property is of the UserInfo class.

You can use the Data property to access any object-specific values of the searched items.

Preparing the SearchParameters object

Search is performed by passing a SearchParameters object to the SearchHelper.Search method. The object contains all information required by the system to complete the search operation. Since the SearchParameters object is complex and requires a large amount of contextual information, the system provides the SearchParameters.PrepareForPages method to facilitate its creation. The method takes the following parameters:

ParameterTypeDescription

searchText

OR

searchPattern

string

OR

SearchPattern

The search query. See Smart search syntax for a reference of supported syntax.

Hotfix 12.0.32 or newer required

The method overload that accepts the SearchPattern parameter is available after installing hotfix 12.0.32 or newer.

You can specify the search query using a SearchPattern object, which consists of the following:

  • SearchText – the search query to search for in the given indexes.
  • SupportedSearchSyntax – an object of the SearchOptionsEnum type that sets the level of supported Lucene syntax for the search query.

SearchOptionsEnum allows the following options:

  • NoneSearch – the search does not recognize any Lucene query syntax. The system processes all text entered by users as a part of the search expression.
  • BasicSearch – the search recognizes all query syntax, except for field search.
  • FullSearch – the search processes all search query syntax, including field search.
searchIndexNamesIEnumerable<string>Code names of the indexes to search.
pageNumberintThe page number of paginated results to retrieve starting from 1.
pageSizeintThe number of results on each page.
userIUserInfoThe user for whom to filter the search results. For example, filters out pages the user is not authorized to view.
cultureNamestringCulture code of the culture to search in. If null, searches in all cultures.
combineWithDefaultCultureboolIndicates whether the search service uses site default language version of pages as a replacement for pages that are not translated into the language specified by cultureName.

Example – Building a search interface on MVC sites

The following search example uses an index that indexes pages (TreeNode objects) and products (SKUTreeNode objects). The example does not use pagination when displaying search result items.

  1. Open your MVC project in Visual Studio.
  2. Create a new model class for working with search queries and search result items.

    using System.Collections.Generic;
    using CMS.Search;

        public class SearchResultModel
        {
            public string Query { get; set; }
            
            public IEnumerable<SearchResultItem> Items { get; set; }
        }
    

  3. Create a controller with an action that searches and provides search results.

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
     
    using CMS.Membership;
    using CMS.Search;
    
            // Adds the smart search indexes that will be used to perform searches
            public static readonly string[] searchIndexes = new string[] { "MVCSite.Index" };
            // Sets the limit of items per page of search results
            private const int PAGE_SIZE = 10;
     
            /// <summary>
            /// Performs a search and displays its result.
            /// </summary>
            [ValidateInput(false)]
            public ActionResult SearchIndex(string searchText)
            {
                // Displays the search page without any search results if the query is empty
                if (String.IsNullOrWhiteSpace(searchText))
                {
                    // Creates a model representing empty search results
                    SearchResultModel emptyModel = new SearchResultModel
                    {
                        Items = new List<SearchResultItem>(),
                        Query = String.Empty
                    };
     
                    return View(emptyModel);
                }
     
                // Searches the specified index and gets the matching results
                SearchParameters searchParameters = SearchParameters.PrepareForPages(searchText, searchIndexes, 1, PAGE_SIZE, MembershipContext.AuthenticatedUser, "en-us", true);
                SearchResult searchResult = SearchHelper.Search(searchParameters);
                
                // Creates a model with the search result items
                SearchResultModel model = new SearchResultModel
                {
                    Items = searchResult.Items,
                    Query = searchText
                };            
     
                return View(model);
            }
    

  4. Add a search input field to one of your site's views. For example:

    @using (Html.BeginForm("SearchIndex", "Search", FormMethod.Get))
    {
        <input type="text" name="searchtext" placeholder="Search..." maxlength="1000">
        <input type="submit" value="Search">
    }
    

  5. Create a view that displays the search result items provided by your search controller. For example:

    @model SearchResultModel
     
    @using CMS.Search;
     
    @if (!Model.Items.Any())
    {
        if (!String.IsNullOrWhiteSpace(Model.Query))
        {
            <h3>No results found for "@Model.Query"</h3>
        }
    }
    else
    {
        <h3>Results for "@Model.Query"</h3>
        foreach (SearchResultItem item in Model.Items)
        {
        <div>
            <strong>@item.Title</strong>
        </div>
        <div>
            @Html.Kentico().ResolveUrls(item.Content)
        </div>
        }
    }
    

Your visitors can now search on your website through the created search field. The system searches through the specified indexes and displays the results.


Was this page helpful?