Date Ranges Using the Sitecore Query Builder

Recently I needed to set the search scope for a Sitecore SXA search component to show only items after today - a common requirement for things like upcoming events where we need past events to fall off the list. Using the Sitecore SXA search components required the use of a search scope, which is nothing more than a Sitecore query builder field.

I had some options here:

  1. Grab all the data and filter the result set by customizing the SXA QueryBuilder JavaScript components and make a big mess
  2. Find a better, cleaner way.

After spending much time getting lost in Google and blog posts, there was a throwaway line at the end of a StackExchange answer that said that you can use Solr queries directly in your search scopes.

Okay cool. I can definitely do a Solr query to do date ranges. In fact, Solr provides a whole page of documentation on dates. Great, I’ll just throw in the Solr query and we’re done!

custom:start_date|[NOW TO *]

The end! Everyone lives happily ever after.


Given that this isn’t the end of the blog post, you can guess that it didn’t “just work”. It didn’t parse my date range! Errors galore! Give up, George, this is a lost cause.

My stubborness took hold and I decided I HAD to find a way. I wanted to know how Sitecore was translating these Sitecore queries into Solr queries under the covers. I just had to know.

And so, out came the decompiler wild guesses because using a decompiler goes against Sitecore terms of use.

I found where the predicates were being built based off of the query (Sitecore.ContentSearch.Utilities.QueryBuilder.BuildMustPredicate, et al.) and there I found how it parses the dates. Jackpot!

Deep in the bowels of those methods, I found a reference to a global variable that’s just…there:

private readonly string DateCompareIdentifier = "#datecompare#";

WAIT - WHAT IS THAT?!

Turns out, that’s the magic string that makes date compare parsing possible. The parser looks for this magic #datecompare# token to recognize it as what I want it to be - a date range. So, to do my little date range that I wanted to do, this had to go into the query builder for the SXA search scope:

custom:start_date|#datecompare#[NOW TO *]

And like magic, Sitecore decided to parse things correctly and I could finally sleep.

If you ever need to query for a date range, make sure you use this magic token!