Return to doc.sitecore.com

Valid for Sitecore 6.0.0, 5.3.2
Using Sitecore Query
Prev Next

The main purpose of Sitecore Queries is to retrieve and filter Items from the Sitecore Database. Sitecore Queries are similar to XPath and SQL ‘select’ statements in many ways. The most straight-forward use of Queries is the identification of a path to an Item. The result yields the children of the specified Item.

/sitecore/content/Home/Coworkers

The query in the example above selects the children of the Coworkers Item.

If it is required to obtain some specific Items and perform filtering, you should use the ‘query’ keyword and additional attributes and modifiers. Please refer to the Query Syntax section below for more details.

For instance, consider a task which requires the selection of all workers from the Sales department whose names start with ‘A’.  This can be achieved with the following query:

query:/sitecore/content/Home/Employees/*[@Department=’Sales’ and startswith(@EmployeeName, 'A')]

  For the sake of convenience, the XPath language has been taken as a base for Sitecore Query expressions. Thus, query expressions work with the Sitecore content like the select sql syntax works with databases.

  Queries are most often used for populating the lists in lookup-type Sitecore fields and also in the API.

  The API usage example below selects descendants of the 'home' Item which are not hidden:   

Item[] Items = Sitecore.Context.Database.SelectItems("/sitecore/content/home//*[@IsHidden != 1]");

 It is possible to pass the parameters along with the queries when working with the API. In the example below, we will create a list of goods and pass the parameter which defines the color of the wrapping:  

string strQuery = "/sitecore/content/Home/Goods/descendant::*[@@name='Shoes' and @color=$color]";
Query query = new Query(strQuery);
query.Parameters.Add("color", "Red");
QueryContext queryContext = new QueryContext(Sitecore.Context.Database.DataManager);
query.Execute(queryContext);

Similarly to XPath, Sitecore Queries are processed in the server side code.

Sitecore Queries are used for populating the lists in lookup-type Sitecore fields and also in the API.

As with many other frameworks, one needs a bit of insight in internal processes to create effective solutions

Sitecore Query uses a path notation, similar to XPath expressions, for addressing Items of a Sitecore content tree


Prev Next