skip to Main Content

I have a search that I’m wanting to exclude any search result that has the name of the “Title” field in the search. For example, say I type in “Contact” in the search bar. I don’t want the Contact Us page to come up, but if someone wants to search something that has words in the Contact Us page, then its ok. I am able to get templateName and IDs but can’t seem to get fields…

Item homeItem = Main.Utilities.SitecoreUtils.getHomeItem();

var query = PredicateBuilder.True<SearchResultItem>();
query = query.And(i => i.Paths.Contains(homeItem.ID));
query = query.And(i => i.Content.Contains(searchTerm));
query = query.And(i => i.TemplateName != "MenuFolder");

This is what I have, but I want to add something to it to exclude the “Title” field and maybe the “SEO” field. So probably something like:

query = query.And(i => i.Fields["Title"]; 

But in this case its including not excluding it. And I can’t do:

query = query.And(i != i.Fields["Title"];

It won’t accept that answer.

2

Answers


  1. Try to use code like that i => !i["Title"].Contains(searchTerm):

    Item homeItem = Main.Utilities.SitecoreUtils.getHomeItem();
    
    var query = PredicateBuilder.True<SearchResultItem>();
    query = query.And(i => i.Paths.Contains(homeItem.ID));
    query = query.And(i => i.Content.Contains(searchTerm));
    query = query.And(i => i.TemplateName != "MenuFolder");
    
    query = query.And(i => !i["Title"].Contains(searchTerm));
    
    Login or Signup to reply.
  2. If you want to strongly type it, you just need to extend the SearchResultItem class with your field name.

    public class SitecoreItem : SearchResultItem
    {
    [IndexField("title")]        
    public string Title { get; set; }
    
    [IndexField("__smallcreateddate")]
    public DateTime PublishDate { get; set; }
    
    [IndexField("has_presentation")]
    public bool HasPresentation { get; set; }
    
    }
    

    Then your code would be like this

    IQueryable<SitecoreItem> query = context.GetQueryable<SitecoreItem>();
    
    SearchResults<SitecoreItem> results = null;
    query = query.Where(x => x.Title.Contains(searchText);
    
    results = query.GetResults();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search