Insights

New Sitecore 7 Feature: Predefined Queries

Great Way To Simplify Your ContentSearch API Calls

Predefined queries were introduced in Sitecore 7 Update 1. They're a very powerful slight of hand. Any object returned by the ContentSearch API (inherits SearchResultItem) can now be decorated with PredefinedQuery attribute that gets added to any query.

This allows to streamline our LINQ queries by pushing filtering logic into our domain objects. Pretty slick. Let's start with a simple class with one decorator:

 

  
[PredefinedQuery("_templatename", ComparisonType.Equal, "product"]
public class Product : SearchResultItem
{
    public string Name { get; set; }
    public string Description { get; set; }
}


We can now simplify our LINQ query because all Product queries will have _templatename == "product" added automatically.

   

// Before PredefinedQuery 
var results = context.GetQueryable()
                    .Where(item => item.TemplateName == "Product")
                    .ToList();

// After!!
var results = context.GetQueryable().ToList(); 

This can become even more powerful by stacking PredefinedQuery attributes. Now without modifying our query we're able to scope our results to Products that are active.

   

[PredefinedQuery("_templatename", ComparisonType.Equal, "product"]
[PredefinedQuery("active", ComparisonType.Equal, "1"]
public class Product : SearchResultItem
{
    public string Name { get; set; }
    public string Description { get; set; }
}


Note

The field names are the index-based field names declared in the <fieldMap /> and <fields hint="raw:AddComputedIndexField /> sections (among others) of your ContentSearch config. So key off the index fields, not the Sitecore fields.

Have fun with it.

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting
 

Meet Dan Cruickshank

President | Sitecore MVP x 11

Dan is the founder of Fishtank. He's a multi-time Sitecore MVP and Coveo MVP award winner. Outside of technology, he is widely considered to be a top 3 father (routinely receiving "Father of the Year" accolades from his family) and past his prime on the basketball court.

Connect with Dan