Queries content items in Orchard Core using YesSql indexes (ContentItemIndex, custom indexes), ISession, IContentManager, and the Queries module's saved SQL queries with Cyqwel parser, IQueryManager, IQuerySource, and the Liquid query filter.
Ships in orchardcore. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an Orchard Core expert. Generate code for querying content items using YesSql indexes and IContentManager.
ISession is the primary interface for querying YesSql indexes.ContentItemIndex is the built-in index for all content items. It declares SingleRecordPerDocument() and ExclusiveToDocumentType() (YesSql 6.3), as do ContainedPartIndex and LocalizedContentItemIndex: a query that only joins these indexes isn't grouped by document, and its count reads the index tables without joining Document..ExclusiveToDocumentType() and .SingleRecordPerDocument() on your own map index providers when true (see orchardcore-yessql-indexes). Use SkipDeduplication() instead of the obsolete NoDuplicates(), and NoIndexOptimizations() for a query the declarations make slower.IContentManager provides higher-level content operations (Get, New, Create, Publish).async/await patterns for database queries..With<IndexType>() to join against specific indexes.&& / ||, but avoid ternaries and other conditional expressions inside query lambdas.CreateMapIndexTableAsync() and AlterIndexTableAsync() for custom YesSql migrations; do not use nameof(...).MapIndex tables already include the DocumentId column automatically, so do not add it manually in the migration."Query" and "index" mean three different things in Orchard Core. Pick the one that matches the goal.
| Goal | Mechanism | Skill |
|---|---|---|
| Fast relational lookup from C# by a column | YesSql MapIndex table + ISession.Query<T, TIndex>() | this skill, orchardcore-yessql-indexes |
Named, stored query run from Liquid, Razor, GraphQL or api/queries | Queries module (IQueryManager, Sql, Lucene, Elasticsearch sources) | this skill |
| Full-text search over content | Index profiles fed by index handlers | orchardcore-indexing, orchardcore-search-indexing |
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Records;
using YesSql;
public sealed class ContentQueryService
{
private readonly ISession _session;
public ContentQueryService(ISession session)
{
_session = session;
}
// Query by content type
public async Task<IEnumerable<ContentItem>> GetByTypeAsync(string contentType)
{
return await _session
.Query<ContentItem, ContentItemIndex>(x => x.ContentType == contentType && x.Published)
.ListAsync();
}
// Query by content type with paging
public async Task<IEnumerable<ContentItem>> GetPagedAsync(string contentType, int page, int pageSize)
{
return await _session
.Query<ContentItem, ContentItemIndex>(x => x.ContentType == contentType && x.Published)
.OrderByDescending(x => x.CreatedUtc)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ListAsync();
}
// Query by display text
public async Task<ContentItem> GetByDisplayTextAsync(string displayText)
{
return await _session
.Query<ContentItem, ContentItemIndex>(x => x.DisplayText == displayText && x.Published)
.FirstOrDefaultAsync();
}
// Count content items
public async Task<int> CountByTypeAsync(string contentType)
{
return await _session
.Query<ContentItem, ContentItemIndex>(x => x.ContentType == contentType && x.Published)
.CountAsync();
}
// Query latest versions (including drafts)
public async Task<IEnumerable<ContentItem>> GetLatestAsync(string contentType)
{
return await _session
.Query<ContentItem, ContentItemIndex>(x => x.ContentType == contentType && x.Latest)
.ListAsync();
}
}
The built-in ContentItemIndex has these fields:
ContentItemId — Unique content item identifier.ContentItemVersionId — Version-specific identifier.ContentType — The content type name.DisplayText — The display text (usually from TitlePart).Published — Whether this version is the published one.Latest — Whether this version is the latest one.CreatedUtc — When the content item was created.ModifiedUtc — When the content item was last modified.PublishedUtc — When the content item was published.Owner — The owner user ID.Author — The author user name.In Orchard Core 4.0 the SQL indexes of ContentItemIndex are IDX_FK_ContentItemIndex (created by YesSql on DocumentId), IDX_ContentItemIndex_DocumentId_ContentType (DocumentId, ContentType, CreatedUtc, ModifiedUtc, PublishedUtc, Published, Latest), IDX_ContentItemIndex_ContentItemId (ContentItemId, DocumentId, Published, Latest), IDX_ContentItemIndex_ContentType (ContentType, DocumentId, Published, Latest), IDX_ContentItemIndex_Owner (Owner, DocumentId, Published, Latest) and IDX_ContentItemIndex_ContentItemVersionId (ContentItemVersionId, DocumentId), plus IDX_ContentItemIndex_ModifiedUtc (ModifiedUtc, DocumentId, Latest, Published, ContentType) and IDX_ContentItemIndex_ContentType_ModifiedUtc (ContentType, ModifiedUtc, DocumentId, Latest, Published) that serve the content items admin list order. Filters on one content type (admin list and its count, GraphQL, pickers, sitemaps), on the owner, on a content item id, or on a version id (GetVersionAsync, loading Lucene or Elasticsearch results) now seek instead of scanning. The 3.x indexes IDX_ContentItemIndex_DocumentId, IDX_ContentItemIndex_DocumentId_Owner, IDX_ContentItemIndex_DocumentId_Author and IDX_ContentItemIndex_DocumentId_DisplayText are dropped. To filter on another column, such as Author or DisplayText, add your own index from a data migration with SchemaBuilder.AlterIndexTableAsync<ContentItemIndex>(). Existing tenants get these changes through migration steps (versions 8 and 9). On a large table they take a moment; with YesSql 6.3 they no longer block writes on SQL Server editions with online index operations and on MySQL, but still do on PostgreSQL and SQLite. Prefer filtering on ContentItemId, ContentType or Owner together with Published or Latest.
using OrchardCore.ContentManagement;
using YesSql.Indexes;
public sealed class {{PartName}}Index : MapIndex
{
public string ContentItemId { get; set; }
public string {{PropertyName}} { get; set; }
public bool Published { get; set; }
}
public sealed class {{PartName}}IndexProvider : IndexProvider<ContentItem>
{
public override void Describe(DescribeContext<ContentItem> context)
{
// A content item has one {{PartName}}, so the index holds at most one record per version.
context.For<{{PartName}}Index>()
.ExclusiveToDocumentType()
.SingleRecordPerDocument()
.When(contentItem => contentItem.Has<{{PartName}}>())
.Map(contentItem =>
{
if (!contentItem.TryGet<{{PartName}}>(out var part))
{
return null;
}
return new {{PartName}}Index
{
ContentItemId = contentItem.ContentItemId,
{{PropertyName}} = part.{{PropertyName}},
Published = contentItem.Published
};
});
}
}
using OrchardCore.Data.Migration;
using YesSql.Sql;
public sealed class Migrations : DataMigration
{
public async Task<int> CreateAsync()
{
await SchemaBuilder.CreateMapIndexTableAsync<{{PartName}}Index>(table => table
.Column<string>("ContentItemId", col => col.WithLength(26))
.Column<string>("{{PropertyName}}", col => col.WithLength(256))
.Column<bool>("Published")
);
await SchemaBuilder.AlterIndexTableAsync<{{PartName}}Index>(table => table
.CreateIndex("IDX_{{PartName}}Index_{{PropertyName}}",
"{{PropertyName}}",
"Published"));
return 1;
}
}
using OrchardCore.Data.Migration;
using YesSql.Indexes;
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddIndexProvider<{{PartName}}IndexProvider>();
services.AddDataMigration<Migrations>();
}
}
public sealed class {{PartName}}QueryService
{
private readonly ISession _session;
public {{PartName}}QueryService(ISession session)
{
_session = session;
}
public async Task<IEnumerable<ContentItem>> GetByPropertyAsync(string value)
{
return await _session
.Query<ContentItem, {{PartName}}Index>(x => x.{{PropertyName}} == value && x.Published)
.ListAsync();
}
}
using OrchardCore.ContentManagement;
public sealed class ContentService
{
private readonly IContentManager _contentManager;
public ContentService(IContentManager contentManager)
{
_contentManager = contentManager;
}
// Get by ID
public async Task<ContentItem> GetByIdAsync(string contentItemId)
{
return await _contentManager.GetAsync(contentItemId);
}
// Get specific version
public async Task<ContentItem> GetVersionAsync(string versionId)
{
return await _contentManager.GetVersionAsync(versionId);
}
// Create new content item
public async Task<ContentItem> CreateAsync(string contentType)
{
var contentItem = await _contentManager.NewAsync(contentType);
await _contentManager.CreateAsync(contentItem, VersionOptions.Draft);
return contentItem;
}
// Publish a content item
public async Task PublishAsync(ContentItem contentItem)
{
await _contentManager.PublishAsync(contentItem);
}
// Update content item
public async Task UpdateAsync(ContentItem contentItem)
{
await _contentManager.UpdateAsync(contentItem);
}
// Remove content item
public async Task RemoveAsync(ContentItem contentItem)
{
await _contentManager.RemoveAsync(contentItem);
}
}
using YesSql;
public sealed class AdvancedQueryService
{
private readonly ISession _session;
public AdvancedQueryService(ISession session)
{
_session = session;
}
public async Task<IEnumerable<ContentItem>> QueryWithSqlAsync()
{
return await _session
.Query<ContentItem, ContentItemIndex>()
.Where(x => x.Published && x.ContentType == "Article")
.OrderByDescending(x => x.PublishedUtc)
.Take(10)
.ListAsync();
}
}
The SQL Queries feature (OrchardCore.Queries.Sql, depends on OrchardCore.Queries) stores named SQL queries that run against the index tables. They are used from Liquid, Razor, scripting, GraphQL, the api/queries/{name} endpoint, data sources of data pipelines (see orchardcore-data-sources), and widgets.
SELECT statements are supported. INSERT, UPDATE, DELETE, MERGE, TRUNCATE, CREATE, ALTER, DROP, CALL, multiple statements (select ...; delete ...) and mutations nested in CTEs or sub-queries are rejected with "Only SELECT statements are supported."DISTINCT, aggregates such as count(distinct a), GROUP BY, UNION, joins, sub-queries, and LIMIT n OFFSET m (translated per dialect, e.g. OFFSET ... FETCH NEXT on SQL Server).second(), minute(), hour(), day(), month(), year(), now() (UTC), and random() in ORDER BY.DocumentId and check Return documents (ReturnContentItems) to load content items.select DocumentId
from ContentItemIndex
where Published = true and ContentType = @contenttype:'BlogPost'
order by CreatedUtc desc
limit @limit:10
@name or @name:default_value; names are case-sensitive. Always pass user input as parameters.{{ ... }} (SQL injection).{% if limit > 0 %}
select DocumentId from ContentItemIndex where Published = true limit @limit
{% else %}
select DocumentId from ContentItemIndex where Published = true
{% endif %}
{
"steps": [
{
"name": "Feature",
"enable": [ "OrchardCore.Queries", "OrchardCore.Queries.Sql" ]
},
{
"name": "Queries",
"Queries": [
{
"Source": "Sql",
"Name": "RecentBlogPosts",
"Template": "select DocumentId from ContentItemIndex where ContentType = 'BlogPost' and Published = true order by CreatedUtc desc limit @limit:3",
"Schema": "{ \"type\": \"ContentItem/BlogPost\" }",
"ReturnContentItems": true
}
]
}
]
}
{% assign posts = Queries.RecentBlogPosts | query: limit: 5 %}
{% for item in posts %}
{{ item | display_text }}
{% endfor %}
@foreach (var contentItem in await Orchard.ContentQueryAsync("RecentBlogPosts"))
{
@await Orchard.DisplayAsync(contentItem)
}
The executeQuery(name, parameters) scripting function runs a query from JavaScript (workflows, recipes).
api/queries/{name} runs a query with GET or POST; parameters is a JSON object, passed in the query string or as the POST body. The response holds items and count. The caller needs ExecuteApi_{QueryName} (implied by ExecuteApiAll and ManageQueries); a query the caller may not execute returns 404.
POST /api/queries/RecentBlogPosts
Content-Type: application/json
{ "limit": 5 }
In Orchard Core 4.0, the endpoint is split into two actions with endpoint names ApiExecuteQueryGet and ApiExecuteQueryPost (route, verbs and parameters unchanged), so OpenAPI documents are valid (see orchardcore-openapi).
| Permission | Member |
|---|---|
| Manage SQL Queries (security critical) | OrchardCore.Queries.QueriesPermissions.ManageSqlQueries |
| Manage queries | OrchardCore.Queries.QueryPermissions.ManageQueries |
| Execute Api - All queries | OrchardCore.Queries.QueryPermissions.ExecuteApiAll |
| Execute Api - {name} | QueryPermissions.CreatePermissionForQuery(name) |
Since Orchard Core 4.0, the GraphQL fields that expose named SQL, Lucene and Elasticsearch queries also require ExecuteApi_{QueryName}, like the REST endpoint.
IQueryManager (namespace OrchardCore.Queries) creates, stores and runs named queries. ExecuteQueryAsync resolves the IQuerySource keyed by Query.Source.
using System.Text.Json.Nodes;
using OrchardCore.ContentManagement;
using OrchardCore.Queries;
public sealed class RecentPostsService
{
private readonly IQueryManager _queryManager;
public RecentPostsService(IQueryManager queryManager)
{
_queryManager = queryManager;
}
public async Task EnsureQueryAsync()
{
if (await _queryManager.GetQueryAsync("RecentBlogPosts") is not null)
{
return;
}
// The data keys match the recipe step: Name, Template, Schema, ReturnContentItems.
var query = await _queryManager.NewAsync("Sql", new JsonObject
{
["Name"] = "RecentBlogPosts",
["Template"] = "select DocumentId from ContentItemIndex where ContentType = 'BlogPost' and Published = true order by CreatedUtc desc limit @limit:10",
["ReturnContentItems"] = true,
});
await _queryManager.SaveAsync(query);
}
public async Task<IEnumerable<ContentItem>> GetRecentAsync(int limit)
{
var query = await _queryManager.GetQueryAsync("RecentBlogPosts");
var results = await _queryManager.ExecuteQueryAsync(query, new Dictionary<string, object>
{
["limit"] = limit,
});
return results.Items.OfType<ContentItem>();
}
}
| Member | Purpose |
|---|---|
NewAsync(source, data) | Build a query for a registered source; returns null when the source is unknown. |
UpdateAsync(query, data) / SaveAsync(params Query[]) | Persist changes. |
GetQueryAsync(name) / DeleteQueryAsync(params string[]) | Load or remove by name. |
ListQueriesAsync(QueryContext) / PageQueriesAsync(page, pageSize, context) | List queries; the ListQueriesBySourceAsync(source) extension filters by source. |
ExecuteQueryAsync(query, parameters) | Run the query and return IQueryResults.Items. |
How a SQL query executes:
Template (stored in SqlQueryMetadata) is rendered as Liquid with the parameters as Liquid values.ReturnContentItems the DocumentId column (or the first long column) is used to load ContentItem documents; otherwise each row is returned as a JsonObject.Implement IQuerySource and register it with AddQuerySource<T>(name), which registers the source as a keyed service under its name. Pair it with a DisplayDriver<Query> for the admin editor and an IQueryHandler (or QueryHandlerBase) that copies source-specific data from the recipe or editor JSON into the query.
using System.Text.Json.Nodes;
using OrchardCore.Entities;
using OrchardCore.Queries;
using OrchardCore.Queries.Core;
public sealed class ProductQueryMetadata
{
public string Filter { get; set; }
}
public sealed class ProductQueryResults : IQueryResults
{
public IEnumerable<object> Items { get; set; } = [];
}
public sealed class ProductQuerySource : IQuerySource
{
public const string SourceName = "Products";
public string Name => SourceName;
public Task<IQueryResults> ExecuteQueryAsync(Query query, IDictionary<string, object> parameters)
{
var metadata = query.GetOrCreate<ProductQueryMetadata>();
// Run the query against your store using metadata.Filter and the parameters.
IQueryResults results = new ProductQueryResults();
return Task.FromResult(results);
}
}
public sealed class ProductQueryHandler : QueryHandlerBase
{
public override Task InitializingAsync(InitializingQueryContext context)
=> CopyAsync(context);
public override Task UpdatingAsync(UpdatingQueryContext context)
=> CopyAsync(context);
private static Task CopyAsync(DataQueryContextBase context)
{
if (context.Query.Source != ProductQuerySource.SourceName)
{
return Task.CompletedTask;
}
var filter = context.Data?[nameof(ProductQueryMetadata.Filter)]?.GetValue<string>();
if (!string.IsNullOrEmpty(filter))
{
context.Query.Put(new ProductQueryMetadata { Filter = filter });
}
return Task.CompletedTask;
}
}
[RequireFeatures("OrchardCore.Queries")]
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddQuerySource<ProductQuerySource>(ProductQuerySource.SourceName);
services.AddScoped<IQueryHandler, ProductQueryHandler>();
// Your DisplayDriver<Query> that renders the Filter editor.
services.AddDisplayDriver<Query, ProductQueryDisplayDriver>();
}
}
IQueryHandler exposes InitializingAsync, InitializedAsync, LoadedAsync, UpdatingAsync, UpdatedAsync, DeletingAsync and DeletedAsync. Every handler sees every query, so check context.Query.Source first.
OrchardCore.Queries.Sql.Permissions.ManageSqlQueries was removed; use OrchardCore.Queries.QueriesPermissions.ManageSqlQueries (stored permission names are unchanged).SqlAst, SqlTranslator, ParlotSqlParser, SqlParserException) was replaced by Cyqwel. Non-SELECT statements, which were never intended, now fail to parse; review queries that relied on lenient parsing.ContentItemIndex loses its DocumentId-led Owner, Author and DisplayText indexes and gains indexes led by ContentType, Owner and ContentItemVersionId. Saved SQL queries or custom code filtering on Author or DisplayText on large tables should add their own index in a migration.IQuery<T>.NoDuplicates() is obsolete, use SkipDeduplication(). A query that skips the deduplication is counted with count(*), so a document it returns several times is counted several times. Queries joining only ContentItemIndex, ContainedPartIndex or LocalizedContentItemIndex are no longer grouped by document; add NoIndexOptimizations() to a query (such as a rare-match text search) that becomes slower. Items with the same modified date in the content items admin list are now ordered by DocumentId descending.api/queries/{name} get new method names (ApiExecuteQueryGet, ApiExecuteQueryPost, previously ApiExecuteQuery) on regeneration.Official Orchard Core videos shown on the documentation page:
What SKILL.md sets; muted values are Claude Code's defaults
/orchardcore:orchardcore-content-queriesfrom orchardcore
npx claudepluginhub crestapps/crestapps.agentskills --plugin orchardcore140 skills in this plugin
/orchardcore-adminGuidance for the Orchard Core admin panel, including admin controllers and routes, admin menu registration with AdminNavigationProvider, ocat editor forms grouped in cards, admin pages rendering Model.Editor, the UI text casing standard, TheAdmin layout and menu colors, admin branding, the Navbar shape, the Ctrl+K quick navigation palette and QuickNavigationSource, AdminSettings such as MenuBehavior, ShowBreadcrumb, DisplayQuickNavigation, DisplayTitlesInTopbar and ActionsLayout, the AdminDashboard shape, settings pages, and admin filters and zones. Use this skill when requests mention the Orchard Core admin panel, TheAdmin, admin controllers, admin menu registration, an icon on an admin menu item, the AdminSettings recipe step, quick navigation, navigation menu behavior, the admin URL prefix, UI text casing. Strong matches include OrchardCore.Admin, AdminSettings, AdminPermissions, AdminOptions, AdminAttribute, SiteDisplayDriver, IDisplayManager./orchardcore-admin-dashboardSkill for creating admin dashboard widgets in Orchard Core. Covers the DashboardWidget stereotype, DashboardPart position and sizing, the built-in HtmlDashboardWidget, ContentsMetadata and ContentsTags widget types, custom widget content types via recipe or migration, arranging widgets in Manage Dashboard mode, widget template customization, provisioning widgets with recipes, dashboard permissions, the DashboardBreadcrumbProvider Dashboard ancestor, and the AdminDashboardContent shape used when the feature is disabled. Use this skill when requests mention Orchard Core Admin Dashboard, Create and Configure Dashboard Widgets, Enabling Admin Dashboard, Widget Configuration Properties, dashboard widget recipes, Dashboard breadcrumb, or related implementation, setup, or troubleshooting work. Strong matches include OrchardCore.AdminDashboard, DashboardPart, DashboardBreadcrumbProvider, AccessAdminDashboard, ManageAdminDashboard./orchardcore-admin-edit-viewsSkill for writing Orchard Core admin editor views with the ocat CSS classes and cards. Covers Edit views for content parts and fields, field editor variants, part, field and site settings editors, Fields.Edit views, admin pages rendering Model.Editor built with IDisplayManager, the ocat classes and their layout rules, label associations and group captions, part and field wrapper classes, validation, hints and the Hint_Admin shape, cards declared in placement and the Card and CardContainer shapes, split editor shapes, tabs and columns, the edit page action bar, the horizontal form layout, and the UI text casing standard. Use this skill when requests mention Orchard Core admin edit views, admin forms, grouping fields in cards, Edit.cshtml, Fields.Edit.cshtml, Settings.Edit.cshtml, ocat classes, label casing, or field hints. Strong matches include ocat-wrapper, ocat-card, Hint_Admin, PlacementLocationBuilder, IDisplayManager, ContentPartDisplayDriver, SiteDisplayDriver./orchardcore-admin-listsSkill for Orchard Core 4.0 admin index views (list pages) rendered with the AdminList shape. Covers the List and Grid layouts, AdminListContext of TModel, the admin-list and admin-list-column tag helpers, column width and alignment, row display drivers placing shapes for SummaryAdmin and SummaryAdminGrid, row templates and zones, AdminListActions Buttons and Menu layouts, AdminListToolbar, AdminListSearch, the list-management script for select-all and bulk actions, IAdminListColumnsProvider, AdminListOptions, user layout selection, per-list alternates, sortable lists, and upgrading overridden list views. Use this skill when requests mention Orchard Core admin index views, an admin index page, admin lists, converting a hand-written admin listing, grid layout, list columns, row actions menu, or adding a column to the content items list. Strong matches include OrchardCore.Admin.Abstractions, AdminListContext, AdminListColumn, IAdminListColumnsProvider, AdminListOptions, AdminListLayout, ContentsAdminList./orchardcore-admin-menuSkill for creating admin menus in Orchard Core. Covers admin menu content, the link, placeholder, content types, and lists admin node types, the AdminMenu recipe and deployment step, ManageAdminMenu, ViewAdminMenuAll and per-menu ViewAdminMenu permissions from AdminMenuPermissions, custom admin nodes with AdminNode, IAdminNodeNavigationBuilder and AddAdminNode, data localization of node text, rendering in the 4.0 TheAdmin menu, and upgrading from the removed legacy admin menu layout. Use this skill when requests mention Orchard Core Admin Menu, Create and Manage Admin Menus, Admin Menu Deployment Recipe Step, Built-In Admin Node Types, Custom Admin Node Class, LegacyAdminMenuNavigation, or related implementation, setup, or troubleshooting work. Strong matches include OrchardCore.AdminMenu, OrchardCore.AdminMenu.Abstractions, AdminMenuPermissions, LinkAdminNode, PlaceholderAdminNode, OrchardCore.Lists, OrchardCore.Navigation./orchardcore-admin-schemesSkill for the Orchard Core 4.0 TheAdmin redesign and its admin schemes. Covers scheme records with their four colors, typography, density, corners, horizontal form layout and content width, Design > Themes > Schemes, the default scheme, the per-user scheme picker and its cookie, the seven built-in schemes, the AdminSchemes recipe step and Admin Schemes deployment step, the schemes.css stylesheet, the --ta-* design tokens, ta-content-fluid, dark mode utilities and nested color modes, TheOldAdmin and how to switch to it, and the breaking changes for custom admin themes and Layout overrides. Use this skill when requests mention admin schemes, admin colors, rebranding TheAdmin, dark mode of the admin, the admin content width, the horizontal form layout, TheOldAdmin, or upgrading a custom admin theme to the new TheAdmin. Strong matches include AdminScheme, AdminSchemes, DefaultSchemeId, HorizontalFormLayout, ContentWidth, data-ta-scheme, --ta-primary, ta-content-fluid, TheOldAdmin, and OrchardCore.Themes.TheAdmin.Other plugins' skills for the same job