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).
Prepare a SearchParameters object with the required search inputs and parameters.
Call the SearchHelper.Search method.
ExampleIEnumerable<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 Dataproperty 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 Dataproperty is of the TreeNodeclass. 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 Dataproperty is of the SKUTreeNodeclass.
- If the search indexes users, the run-time type of a search result item’s Dataproperty is of the UserInfoclass.
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:
Parameter |
Type |
Description |
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:
SearchOptionsEnum allows the following options:
|
searchIndexNames |
IEnumerable<string> |
Code names of the indexes to search. |
pageNumber |
int |
The page number of paginated results to retrieve starting from 1. |
pageSize |
int |
The number of results on each page. |
user |
IUserInfo |
The user for whom to filter the search results. For example, filters out pages the user is not authorized to view. |
cultureName |
string |
Culture code of the culture to search in. If null, searches in all cultures. |
combineWithDefaultCulture |
bool |
Indicates 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. |
Number of processed search results
Every search request has a maximum number of processed and returned search results. The purpose of the limit is to avoid processing large numbers of results with low relevance. The limit is determined by the NumberOfProcessedResults property of the SearchParameters object that you use to perform the search.
By default, the SearchParameters.PrepareForPages method sets the NumberOfProcessedResults property to 100. If you use large search indexes that regularly produce more results, you can either set a higher value for the property before calling SearchHelper.Search, or implement search filters to help narrow down the search.
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.
Open your MVC project in Visual Studio.
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; } }
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); }
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"> }
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.