Sunday, May 29, 2011

Sitecore Query

I have come to known this issue whereby Sitecore Query limit the search by default to 100. This means potentially we will get less results than expected. Recently, I have come across a solution where the Query max item is tweaked on the fly.

here is the sample code


///
/// Set Query.MaxItems unlimit
/// Reference : http://blog.bylectric.net/2009/07/sitecore-and-query-maxitems-setting/
///

///
///
///
public static Item[] QueryItemsWithoutLimit(string queryString , Item startRoot )
{
if (string.IsNullOrEmpty(queryString) || startRoot == null)
return null;

Query query = new Query(queryString);
query.GetType().GetField("m_max", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(query, 0);
Object result = query.Execute(startRoot);
QueryContext qc = result as QueryContext;
QueryContext[] qcArray = result as QueryContext[];

var database = global::Sitecore.Context.ContentDatabase ?? global::Sitecore.Context.Database;
if (qcArray != null && qcArray.Length > 0)
{
Item[] itemArray = new Item[qcArray.Length];
for (int i = 0; i < qcArray.Length; i++)
{
itemArray[i] = database.Items[qcArray[i].ID];
}
return itemArray;
}

if (qc != null)
return new Item[] { database.Items[qc.ID] };
return null;
}

No comments:

Post a Comment