Quantcast
Channel: Customized Commerce 13 and earlier versions
Viewing all articles
Browse latest Browse all 9642

How to get occurences of a word from page in CMS

$
0
0

I need to sort the search results based on the occurrence of the keyword. Once we get the result from executing the query, the idea is to get the occurence from the content of the results hits, and then sort results on that basis. I am using below functions to count the occurence, but not getting the right results through it. Has anybody been able to achieve similar functionality?

We are using Find 16.0.1

private int CountTermOccurrences(SearchHit<UnifiedSearchHit> hit, string searchTerm)

{

    // Extract the text content to search for term occurrences

    string contentText = ExtractTextFromContent(hit);

 

    if (string.IsNullOrEmpty(contentText))

    {

        return 0;

    }

 

    // Count occurrences of the search term

    int count = 0;

    int index = contentText.IndexOf(searchTerm, 0, System.StringComparison.OrdinalIgnoreCase);

    while (index != -1)

    {

        count++;

        index = contentText.IndexOf(searchTerm, index + searchTerm.Length, System.StringComparison.OrdinalIgnoreCase);

    }

 

    return count;

}

 

private string ExtractTextFromContent(SearchHit<UnifiedSearchHit> hit)

{

    var content = SearchHelper.GetOriginalObject(hit.Document);

    // Extract text from different properties of the content (e.g., main body, summary, etc.)

    // Customize this method to fit your content model

    var contentData = content as IContentData;

    var textProperties = new List<string>();

 

    if (contentData != null)

    {

        foreach (var property in contentData.Property)

        {

            if (property.PropertyValueType == typeof(string))

            {

                textProperties.Add(property.Value as string);

            }

        }

    }

 

    return string.Join("", textProperties);

}


Viewing all articles
Browse latest Browse all 9642

Trending Articles