Filter Search Results By Tags Using Kentico API

filter-search-results-by-tags-using-kentico-api

In Kentico, filtering search results by tags can be achieved using the built-in functionalities provided by the platform. Here’s a general guide on how to filter search results by tags in Kentico (v12/13).

Tagging Content:
Ensure that your content items are properly tagged with the appropriate tags. You can assign tags to pages, documents, or other content types based on your configuration.

Creating a Custom Search Filter:
You’ll need to create a custom search filter to allow users to search by tags.

Custom Code or Configuration:
Use the Kentico API to query content based on tag information. You can use the DocumentHelper or TreeNode API methods to retrieve content based on tags assigned to the documents.

Filtering search results based on tags using the Kentico API involves querying the content based on the assigned tags.

Below is an example of how you might achieve this using the Kentico API in C#:

using CMS.DocumentEngine;
using CMS.SiteProvider;
using CMS.DocumentHelper;
using CMS.Search;

// Your method to filter search results by tags
public DataSet FilterSearchResultsByTags(string searchTerm, string[] tags)
{
    // Define your search parameters
    SearchParameters parameters = new SearchParameters()
    {
        SearchFor = searchTerm, // The search term entered by the user
        SearchIn = SearchHelper.CombineFields(DocumentHelper.GetSearchFields(SiteContext.CurrentSiteName)), // Search within specific fields
        Culture = SiteContext.CurrentCultureName, // Current culture
        ClassNames = "", // Limit search to specific document types if needed
        CurrentCulture = true
    };

    // Perform the search
    DataSet searchResults = SearchHelper.Search(parameters);

    // Filter search results by tags
    if (searchResults != null && searchResults.Tables.Count > 0)
    {
        DataTable filteredResults = searchResults.Tables[0].Clone(); // Create a copy of the structure

        foreach (DataRow row in searchResults.Tables[0].Rows)
        {
            int documentId = ValidationHelper.GetInteger(row["DocumentID"], 0);

            // Check if the document has any of the specified tags
            if (documentId > 0 && DocumentHelper.GetDocuments()
                .WhereEquals("DocumentID", documentId)
                .OnSite(SiteContext.CurrentSiteName)
                .Culture(SiteContext.CurrentCultureName)
                .CombineWithDefaultCulture(true)
                .Published()
                .WhereIn("DocumentTags", tags)
                .Count > 0)
            {
                filteredResults.ImportRow(row);
            }
        }

        // Return the filtered results
        return new DataSet().AddTable(filteredResults);
    }

    return null;
}

Filter search results based on a certain tag using ISearchRepository

ISearchRepository interface provides methods to perform search-related operations. To filter search results based on a certain tag using ISearchRepository, you’d need to leverage the available methods and parameters to achieve this.

Below is an example demonstrating how you might filter search results based on a specific tag using ISearchRepository in Kentico:

using CMS;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.Search;
using CMS.SiteProvider;
using System;
using System.Linq;

public class MySearchService
{
    private ISearchRepository searchRepository;

    public MySearchService(ISearchRepository searchRepository)
    {
        this.searchRepository = searchRepository ?? throw new ArgumentNullException(nameof(searchRepository));
    }

    public SearchResultItem[] FilterSearchResultsByTag(string searchTerm, string tagName)
    {
        // Get the site ID for the current site
        int siteId = SiteContext.CurrentSiteID;

        // Create search parameters
        var parameters = new SearchParameters()
        {
            SearchFor = searchTerm, // The search term entered by the user
            SearchIndexes = SearchIndexInfoProvider.GetSearchIndexes().WhereEquals("IndexIsSingleNode", false).ToList(), // Get search indexes excluding single-node indexes
            SearchIn = SearchHelper.CombineFields(DocumentHelper.GetSearchFields(SiteContext.CurrentSiteName)), // Search within specific fields
            ClassNames = "", // Limit search to specific document types if needed
            CheckPermissions = true,
            Culture = SiteContext.CurrentCulture.CultureCode,
            CurrentCulture = true,
            DefaultCulture = true,
            CombineWithDefaultCulture = true,
            StartingPath = "/", // Set the starting path for the search
            NumberOfResults = 100 // Set the number of search results to retrieve
        };

        // Perform the search
        var searchResults = searchRepository.Search(parameters).Items;

        // Filter search results by the specified tag
        var filteredResults = searchResults.Where(result =>
        {
            var document = DocumentHelper.GetDocument(result.Id, new TreeProvider());
            if (document != null)
            {
                // Check if the document has the specified tag
                return DocumentTagInfoProvider.GetDocumentTags(result.Id, siteId)
                            .Any(tag => string.Equals(tag.TagName, tagName, StringComparison.InvariantCultureIgnoreCase));
            }
            return false;
        }).ToArray();

        return filteredResults;
    }
}

Replace searchTerm with the term entered by the user.
Replace tagName with the specific tag name you want to filter by.
Adjust the SearchIndexes, SearchIn, ClassNames, and other search parameters based on your Kentico configuration and requirements.

This code performs a search using the ISearchRepository, retrieves the search results, and then filters them based on the specified tag name associated with the documents.

Make sure to handle exceptions and adapt the code according to your Kentico setup and project structure.