Thursday, October 13, 2011

Sitecore Search - MustNot Query

From personal experience, it seems that it is not possible to run a Sitecore.Search.CombinedQuery using only a single fieldquery set to Sitecore.Search.QueryOccurance.MustNot.  For example, if you wanted to run a query against an index that returned items that didn't have a value of "1" (checked) in an "Inactive" checkbox field, you might try doing:

Sitecore.Search.CombinedQuery completequery = new Sitecore.Search.CombinedQuery();

Sitecore.Search.QueryBase fq1 = new Sitecore.Search.FieldQuery("Inactive", "1");
completequery.Add(fq1, Sitecore.Search.QueryOccurance.MustNot);


var Index = Sitecore.Search.SearchManager.GetIndex(IndexName);
Sitecore.Search.SearchResultCollection results;
using (Sitecore.Search.IndexSearchContext context = new Sitecore.Search.IndexSearchContext(Index))
{
    var hits = context.Search(completequery);
    results = hits.FetchResults(0, hits.Length);
}


However, this will not ever return results by itself - again, because it seems like a MustNot cannot be the lone clause in a CombinedQuery.  An easy way around this is to add the following code (where TemplateID = the ID of the template from your index):

//Have to have a "Must" query - the lone MustNot for fq1 will not work by itself.  This is simply a "placeholder" type query that supplies the "Must"
//By itself, this query should not eliminate nor incorporate any additional records from the index.
Sitecore.Search.QueryBase fq0 = new Sitecore.Search.FieldQuery(Sitecore.Search.BuiltinFields.Template,Sitecore.Data.ShortID.Encode(TemplateID).ToLowerInvariant());
completequery.Add(fq0, Sitecore.Search.QueryOccurance.Must);

No comments:

Post a Comment