Reference - Content item query
This page provides information about the parameterization methods available for the Content item API. The methods allow you to adjust queries and limit which items are retrieved or specify which columns are loaded to improve performance, for example.
ContentItemQueryBuilder methods
ForContentType
Retrieves all items of the specified content type. Generates a subquery that can be further configured. See Content query parameterization and ForContentType parameterization.
var builder = new ContentItemQueryBuilder();
// Retrieves all content items of the 'Sample.Type' type
builder.ForContentType("Sample.Type");
ForContentTypes
Retrieves all content items across all content types. Use the method’s inner parameterization to limit the selection to a subset of items.
Does not include content type field data and web page data by default. Use WithContentTypeFields or WithWebPageData to include it.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Retrieves all items with the given reusable schema
parameters.OfReusableSchema("PageMetadata");
});
Parameters
Specifies a set of parameters that apply to all items selected by individual subqueries. See Content query parameterization.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type")
.ForContentType("Sample.NewsRelease")
// Sorts all records according to the 'ContentItemName' column
.Parameters(globalParams => globalParams.OrderBy("ContentItemName"))
InLanguage
Selects items from the specified language. Use language code name as specified in the Languages application.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type")
.ForContentType("Sample.NewsRelease")
// Selects only items from the English language
.InLanguage("en");
Content query parameterization
Columns
Limits the columns that are retrieved by the query. See Content item database structure.
If not specified, the query by default includes all columns from all selected content types.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Retrieves only the 'Title' and 'Content' columns from 'Sample.Type'
subqueryParameters.Columns("Title", "Content");
});
If Columns is called multiple times for a content type, columns from all method calls are included.
The method also supports column aliasing:
builder.ForContentType("Sample.Type1", subqueryParameters =>
{
// Aliases 'Type1Title' as 'Title'
subqueryParameters.Columns(QueryColumn.Alias("Type1Title", "Title"));
})
ForContentType("Sample.Type2", subqueryParameters =>
{
// Aliases 'Type2Title' as 'Title'
subqueryParameters.Columns(QueryColumn.Alias("Type2Title", "Title"));
})
// Orders both 'Type1' and 'Type2'
.Parameters(globalParameters => globalParameters.OrderBy("Title"));
Offset
Offsets the records by the specified index
(zero-based) and takes the next X
items specified by fetch
.
Must be used together with OrderBy, otherwise the pagination is not applied (as the system cannot guarantee a deterministic ordering of the returned results).
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Takes the next 5 items starting from the 11th
subqueryParameters.Offset(10, 5);
subqueryParameters.OrderBy("ContentItemName");
});
IncludeTotalCount
Ensures that every retrieved item stores the total number of items, regardless of pagination applied by Offset.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Includes the total number of items
subqueryParameters.IncludeTotalCount()
// Takes the next 5 items starting from the 11th
subqueryParameters.Offset(10, 5);
subqueryParameters.OrderBy("ContentItemName");
});
After executing the query, use GetTotalCount
on an item in the result to get the total number of items.
var items = await queryExecutor.GetResult(builder, item => item);
int? totalItemCount = items.First().GetTotalCount();
TopN
Limits the number of records fetched from the database.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Takes the first 5 results from the selection
subqueryParameters.TopN(5);
});
OrderBy
Allows ordering of the results based on the value of a specified column.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// By default, items in the specified columns are sorted in ascending order
subqueryParameters.OrderBy("ContentItemName");
// You can parameterize the behavior by providing an instance of 'CMS.DataEngine.OrderByColumn'
subqueryParameters.OrderBy(new OrderByColumn("ContentItemName", OrderDirection.Descending));
});
Where
Inserts an SQL WHERE clause into the query.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Retrieves items that have the 'ShowInBanner' property set to true
subqueryParameters.Where(where => where.WhereTrue("ShowInBanner"));
});
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Multiple where operations are implicitly joined by AND
subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
.WhereLike("ColumnB", "value"));
// OR has to be specified explicitly
subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
.Or()
.WhereLike("ColumnB", "value"));
});
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Retrieves items whose name starts with with 'Apple'
subqueryParameters.Where(where => where.WhereStartsWith("ContentItemName", "Apple"));
});
The set of available Where
extensions matches the expressivity of the SQL WHERE syntax. This page provides examples of only a few of the available methods.
WhereContainsTags
Limits the query to content items that contain the specified tags.
// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;
var builder = new ContentItemQueryBuilder()
.ForContentType(
"Some.Type",
subqueryParameters =>
// Retrieves items with the specified tags
subqueryParameters.Where(where =>
where.WhereContainsTags("SomeTaxonomy", tagIdentifiers))
).InLanguage("en");
// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;
var tagCollection = await TagCollection.Create(tagIdentifiers);
var builder = new ContentItemQueryBuilder()
.ForContentType(
ArticlePage.CONTENT_TYPE_NAME,
subqueryParameters =>
// Retrieves items with the specified tags and any child tags
subqueryParameters.Where(where =>
where.WhereContainsTags("SomeTaxonomy", tagCollection))
).InLanguage("en");
ForContentType parameterization
Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentType
call.
ForWebsite
Configures the query to retrieve web pages from a specified website channel. Specify the following parameters:
websiteChannelName
– code name of the website channel from which the pages are retrieved.pathMatch
– a parameter of typePathMatch
used to limit the retrieved pages only to a certain section of the website’s content tree.includeUrlPath
– indicates if the URL path should be included in the retrieved data.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Retrieves pages from the specified website channel
subqueryParameters.ForWebsite(
websiteChannelName: "DancingGoatPages",
pathMatch: PathMatch.Children("/Articles"),
includeUrlPath: true);
});
See Retrieve page content for more information.
WithLinkedItems
Configures query to include linked content items recursively up to the specified depth.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
// Retrieves all linked items up to the maximum depth of 2
subqueryParameters.WithLinkedItems(2);
});
To see how the query result is bound to a model class, check out WithLinkedItems mapping.
Linking
Retrieves all content items from the specified field which reference any of the content items from the provided collection. Enables loading data on-demand (lazily).
var builder = new ContentItemQueryBuilder();
// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
// Retrieves all content items of 'project.staff' type that reference any
// of the items in 'managersCollection' from their 'ManagerField' field
subqueryParameters.Linking("ManagerField", managersCollection);
});
For more information see Linking details.
LinkedFrom
Retrieves content items of a specific type linked from the given field in the provided collection. Enables loading data on-demand (lazily).
var builder = new ContentItemQueryBuilder();
// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
// Items are retrieved for a collection of
// 'project.store' items - 'storesCollection' - and the field 'StaffField'
subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection);
});
For more information see LinkedFrom details.
LinkedFromSchemaField
Retrieves all content items of the type specified in ForContentType
that are linked from a collection of items via a reusable schema field.
var builder = new ContentItemQueryBuilder();
builder.ForContentType("Sample.Type", subqueryParameters =>
{
subqueryParameters.LinkedFromSchemaField("SchemaFieldCodeName", contentItems);
});
For more information see LinkedFromSchemaField details.
ForContentTypes parameterization
Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes
call.
OfContentType
Selects items with the specified content types.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Retrieves items of the 'Acme.Article', 'Acme.Blog' content types
parameters.OfContentType("Acme.Article", "Acme.Blog");
});
OfReusableSchema
Selects items with the specified reusable field schema.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Retrieves items with the 'PageMetadata' reusable field schema
parameters.OfReusableSchema("PageMetadata");
});
ForWebsite
Provides multiple overloads that can:
- select all web pages in the system
- select web pages based on their ID, GUID, or code names
- select web pages from specific channels and paths
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Calls are mutually exclusive
// Shown to demonstrate available overloads
// Retrieves all web pages in the system
parameters.ForWebsite();
// Retrieves pages with the provided GUIDs
// (e.g., from the 'Page selector' component)
parameters.ForWebsite(webPageGuids);
// Retrieves all web pages under the 'Acme' channel and 'Articles' page path
parameters.ForWebsite(
websiteChannelName: "Acme",
pathMatch: PathMatch.Children("/Articles"));
});
Each overload also provides the optional includeUrlPath
path parameter. true
by default, it indicates whether web page URL data should be included in the query.
If you want to retrieve web pages and reusable content items in a single query, see the WithWebPageData method.
WithContentTypeFields
By default, the result returned by ForContentTypes
contains content item metadata (CMS_ContentItem table Content item database structure) and reusable field schema data. WithContentTypeFields
also adds content type-specific fields to the result.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Retrieves items with the 'PageMetadata' reusable field schema
// and includes content-type specific fields in the result
parameters.OfReusableSchema("PageMetadata")
.WithContentTypeFields();
});
WithWebPageData
By default, the result returned by ForContentTypes
contains content item metadata (CMS_ContentItem table Content item database structure) and reusable field schema data. WithWebPageData
also adds website content-specific fields (such as URL and tree path) to the result.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// Retrieves items with the 'PageMetadata' reusable field schema
// and includes web page specific fields in the result
parameters.OfReusableSchema("PageMetadata")
.WithWebPageData();
});
WithLinkedItems
Configures query to include linked content items recursively up to the specified depth. The parameterization behaves identically to its alternative in ForContentType.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
// Retrieves all linked items up to the maximum depth of 2
subqueryParameters
.OfContentType(Article.CONTENT_TYPE_NAME)
.WithLinkedItems(2);
});
If the collection of linked items contains web page items, you need to specify the IncludeWebPageData
option to include web page specific data (such as URL and tree path) of the web page items:
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
// Retrieves all linked items up to the maximum depth of 2
// including web page data of linked web page items
subqueryParameters
.OfContentType(Article.CONTENT_TYPE_NAME)
.WithLinkedItems(2, options => options.IncludeWebPageData());
});
To see how the query result is bound to a model class, check out WithLinkedItems mapping.
Linking
The method behaves identically to ForContentType.Linking, with the following exceptions:
- You need to specify the name of the content type whose items you want to retrieve, in addition to its field. This is necessary to prevent ambiguities in case the searched content types contain identical field names.
- The usage is limited to one
Linking
call for eachForContentTypes
subquery.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
// Retrieves items of the 'Acme.MyItem' type that link to
// any of the content items in 'itemCollection' via their 'MyItemField' field
subqueryParameters.Linking("Acme.MyItem", "MyItemField", itemCollection);
});
For more information see Linking details.
LinkedFrom
The behavior is identical to ForContentType.LinkedFrom, with the only difference being that you cannot chain multiple calls within a single subquery.
For more information see LinkedFrom details.
LinkingSchemaField
Retrieves all content items that link to a collection of items via the specified reusable schema field. LinkedFromSchemaField complements this method by retrieving links from the opposite direction.
var imageIdentifiers = new List<int>() { 1, 2, 3 };
var builder = new ContentItemQueryBuilder().ForContentTypes(q =>
{
q.LinkingSchemaField("ProductImage", imageIdentifiers);
});
For more information see LinkingSchemaField details.
LinkedFromSchemaField
Retrieves all content items that are linked from a collection of items via a reusable schema field. LinkingSchemaField complements this method by retrieving links from the opposite direction.
var builder = new ContentItemQueryBuilder().ForContentTypes(q =>
{
q.LinkedFromSchemaField("ProductImage", productIdentifiers);
});
For more information see LinkedFromSchemaField details.
InSmartFolder
Retrieves content items that fulfill the filter conditions of the specified smart folder. This allows content editors to control which items are retrieved directly in the Content hub UI, without needing to adjust the code.
The smart folder can be specified by its ID, GUID, or code name. You can get the smart folder GUID from a field using the Smart folder selector UI form component. You can also find the identifiers of smart folders in the Content hub application – expand the menu actions of a folder and select Properties.
var builder = new ContentItemQueryBuilder();
// Retrieves content items from the specified smart folder
builder.ForContentTypes(parameters => parameters.InSmartFolder(smartFolderGuid));
The InSmartFolder
parameterization causes the query to return an empty result if the specified smart folder:
- Doesn’t exist
- Doesn’t have dynamic content delivery enabled
- Has invalid filter conditions (for example if a tag saved in the Taxonomy filter option was later deleted)
The following scenarios are unsupported and result in an exception:
- Using multiple
inSmartFolder
calls for a single query - Combining
InSmartFolder
withForWebsite
parameterization (smart folders are only supported for reusable content items, not pages)
If you need to ensure that only items of one specific content type are retrieved (regardless of the smart folder’s filter condition), add OfContentType
to the parameterization.
var builder = new ContentItemQueryBuilder();
// Retrieves items of one specific content type from a smart folder
builder.ForContentTypes(parameters =>
{
parameters.InSmartFolder(smartFolderGuid)
.OfContentType("Sample.Type");
});
Where conditions
Where parameterization can be added to ForContentTypes
queries using Parameters.
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(parameters =>
{
// ...
}).Parameters(parameters =>
{
parameters.Where(where => where) //...
});
Method details
Methods described in this section can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes
call or a ContentItemBuilder.ForContentType
call.
WithLinkedItems
IContentQueryExecutor.GetMappedResult
, IContentQueryExecutor.GetMappedWebPageResult
, or using the provided IContentQueryResultMapper
automatically binds the linked content item hierarchy to the specified model.
IEnumerable<ModelClass> data =
queryExecutor.GetMappedResult<ModelClass>(builder);
When mapping the data manually, use GetLinkedItems
on the result to get the next level of references. This can be repeated up until the specified recursion level.
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);
private ContentItemDto resultSelector(IContentQueryDataContainer itemData)
{
var item = new ContentItemDto
{
Title = itemData.GetValue<string>("Title"),
Text = itemData.GetValue<string>("Text"),
// Retrieves first-level linked items from the 'Author' field
AuthorName = itemData.GetLinkedItems("Author").First()
.GetValue<string>("Name");
// Retrieves second-level linked items from the 'Author' field
AuthorProfileBlurb =
itemData.GetLinkedItems("Author").First()
.GetLinkedItems("Profile").First()
.GetValue<string>("ProfileBlurb");
};
return item;
}
Linking
Retrieves all content items from the specified field which reference any of the content items from the provided collection. Enables loading data on-demand (lazily).
The following diagram illustrates the behavior on a simple content model:
Combining this method with LinkedFrom in a single subquery is not supported.
The method can also be used together with WithLinkedItems
. For example:
var builder = new ContentItemQueryBuilder();
// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
// Items are retrieved for a collection of 'project.store' items and the field 'StaffField'
// together with all first-level references for the selected 'project.staff' items
subqueryParameters.Linking("ManagerField", managersCollection)
.WithLinkedItems(2);
});
The collection of items for which to retrieve references must implement the IContentItemIdentifier
interface. The interface ensures fields required by each data model that wants to leverage this method. The fields must be bound to the model during model binding within ContentQueryExecutor.GetResult
.
Generated content type classes already implement IContentItemIdentifier
via the SystemFields
property. The following approach applies for custom model classes.
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);
ManagerDto resultSelector(IContentQueryDataContainer itemData)
{
var item = new ManagerDto
{
// Binds fields required by 'Linking'
ContentItemID = itemData.ContentItemID,
ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
// other fields...
};
return item;
}
// Example custom model class binding content items of the 'Manager' content type
class ManagerDto : IContentItemIdentifier
{
public int ContentItemID { get; }
public int ContentLanguageID { get; }
public IEnumerable<ContentItemReference> PictureField { get; }
public IEnumerable<ContentItemReference> AwardsField { get; }
}
LinkedFrom
Retrieves content items of a specific type linked from the given field in the provided collection. Enables loading data on-demand (lazily).
The following diagram illustrates the behavior on a simple content model. Red arrows trace query evaluation:
Combining this method with Linking in a single subquery is not supported.
The method can also be used together with WithLinkedItems
. For example:
var builder = new ContentItemQueryBuilder();
// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
// Items are retrieved for a collection of 'project.store' items and the field 'StaffField'
// together with all first-level references for the selected 'project.staff' items
subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection)
.WithLinkedItems(1);
});
The collection of items for which to retrieve references must implement the IContentItemIdentifier
interface. The interface ensures fields required by each data model that wants to leverage this method. The fields must be bound to the model during model binding within ContentQueryExecutor.GetResult
.
Generated content type classes by default implement IContentItemIdentifier
via the SystemFields
property. The following approach applies for custom model classes.
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);
StoreDto resultSelector(IContentQueryDataContainer itemData)
{
var item = new StoreDto
{
// Binds fields required by `LinkedFrom`
ContentItemID = itemData.ContentItemID,
ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
// other fields...
};
return item;
}
// Example custom model class binding content items of the 'Store' content type
class StoreDto : IContentItemIdentifier
{
public int ContentItemID { get; }
public int ContentLanguageID { get; }
public IEnumerable<ContentItemReference> StaffField { get; }
public IEnumerable<ContentItemReference> ReferenceField { get; }
public IEnumerable<ContentItemReference> FaqField { get; }
}
LinkingSchemaField
This method can only be called from within subqueries generated by a ContentItemBuilder.ForContentTypes
call.
Retrieves all content items that link to a collection of items via the specified reusable schema field. LinkedFromSchemaField complements this method by retrieving links from the opposite direction.
See the following diagram for an illustration of the method’s behavior on a simplified content model. The query retrieves all content items that link to the images from imageIdentifiers
via the ProductImage reusable schema field. Red arrows trace the query evaluation:
In the diagram above, the method is called with the following parameters:
"ProductImage"
– the code name of a field that belongs to a reusable field schema. Reusable schema field code names must be unique across the system, it’s therefore sufficient to target fields directly.imageIdentifiers
– IDs of content items with the Image content type.
LinkedFromSchemaField
Retrieves all content items that are linked from a collection of items via a reusable schema field. LinkingSchemaField complements this method by retrieving links from the opposite direction.
See the following diagram for an illustration of the method’s behavior on a simplified content model. The query retrieves all Image content items that are linked from productIdentifiers
via the ProductImage reusable schema field. Red arrows trace the query evaluation:
In the diagram above, the method is called with the following parameters:
"ProductImage"
– the code name of a field that belongs to a reusable field schema. Reusable schema field code names are unique and can be targeted directly without specifying the corresponding schema.productIdentifiers
– a collection of content items from content types using the ProductFields reusable field schema.
The collection of items for which to retrieve references must implement the IContentItemIdentifier
interface. The interface ensures fields required by each data model that wants to leverage this method.
Generated content type classes by default implement IContentItemIdentifier
via the SystemFields
property.
IContentQueryExecutor configuration
Apart from configuring the query itself, you can also fine tune its execution. You can do so by setting the properties of the ContentQueryExecutionOptions
attribute and providing it to the IContentQueryExecutor
interface.
Property | Description |
| If set to true, the query executor retrieves the queried items in their latest available version, regardless of their workflow state. Otherwise, the latest published version is retrieved. Default value: false. |
| If set to true, the query executor retrieves all items according to the query, including secured items. Otherwise, only items that are not secured are included in the query. Default value: false. |
To see how the configuration affects the data retrieval, check out the examples at Retrieve page content.