Search exact term

StanM M asked on June 23, 2020 13:44

I have Kentico 12 MVC project. In the admin I have a page with field MyField. This field is set as Content, Searchable, Tokenized.
Then, I am using Pages search index, standard analyzer. Now, I have pages with these values in MyField:

Page 1: foo
Page 2: foo something
Page 3: foo blahblah
...and so on.

Now, what I want to achieve is when a user will search for "foo", the results will return just page 1. When user will search for "foo something", only page 2 will be returned. Do you have any ideas how to achieve it in MVC code? Maybe using some search condition?

Thanks!

Recent Answers


Dmitry Bastron answered on June 23, 2020 14:29

Hi Stan,

For exact match you can use additional quotes for your search phrase like this:

SearchParameters searchParameters = SearchParameters.PrepareForPages("\"foo something\"", searchIndexes, pageNumber, pageSize, searchUser, cultureCode, combineWithDefaultCulture);
0 votesVote for this answer Mark as a Correct answer

Dmitry Bastron answered on June 23, 2020 17:18

Ok, the following approach should work then:

var searchText = SearchSyntaxHelper.CombineSearchCondition("foo bar",
    new SearchCondition
    {
        DocumentCondition = new DocumentSearchCondition
            {ClassNames = "custom.mypagetype", Culture = "en-US"},
        ExtraConditions =
            SearchSyntaxHelper.GetRequiredCondition(
                SearchSyntaxHelper.GetFilterCondition("MyField", "foo something"))
    });

SearchParameters searchParameters = SearchParameters.PrepareForPages(searchText, searchIndexes, pageNumber, pageSize, searchUser, cultureCode, combineWithDefaultCulture);

The code above will search for:

  • all documents of "custom.mypagetype" page type AND "en-US" culture
  • AND have something of "foo bar" in CONTENT field (you may leave this string empty for your case)
  • AND "foo something" in "MyField" field (you may need to try "\"foo something\"" instead)
1 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.