Orchardcore yessql indexes

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore yessql indexes is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for creating custom YesSql indexes in Orchard Core. Covers MapIndex models, IndexProvider patterns, YesSql 6.3 index declarations (ExclusiveToDocumentType, SingleRecordPerDocument), SkipDeduplication and NoIndexOptimizations queries, multi-row mappings for one-to-many relationships, migration

How to use this skill

Skill file

Orchard Core YesSql Indexes - Prompt Templates

Create a Custom YesSql Index

You are an Orchard Core expert. Generate code for custom YesSql indexes that follows Orchard Core conventions and CrestApps project structure.

Guidelines

Recommended Placement

src/Core/{{FeatureName}}.Core/
  Indexes/
    {{LookupName}}Index.cs
src/Modules/{{FeatureName}}/
  Migrations/
    {{FeatureName}}Migrations.cs
  Startup.cs

Simple Lookup Index

using OrchardCore.ContentManagement;
using YesSql.Indexes;

namespace CrestApps.Sports.Core.Indexes;

public sealed class ClubTeamsIndex : MapIndex
{
    public string ClubContentItemId { get; set; }

    public string TeamContentItemId { get; set; }

    public bool Published { get; set; }
}

public sealed class ClubTeamsIndexProvider : IndexProvider<ContentItem>
{
    public override void Describe(DescribeContext<ContentItem> context)
    {
        // Only content items write records, and a team version maps at most one record.
        context.For<ClubTeamsIndex>()
            .ExclusiveToDocumentType()
            .SingleRecordPerDocument()
            .Map(contentItem =>
            {
                if (contentItem.ContentType != ContentTypes.Team)
                {
                    return null;
                }

                var clubContentItemId = contentItem.GetContentPickerValue("TeamPart", "Club");

                if (string.IsNullOrWhiteSpace(clubContentItemId))
                {
                    return null;
                }

                return new ClubTeamsIndex
                {
                    ClubContentItemId = clubContentItemId,
                    TeamContentItemId = contentItem.ContentItemId,
                    Published = contentItem.Published,
                };
            });
    }
}

One-to-Many Index with Multiple Rows Per Content Item

using OrchardCore.ContentManagement;
using YesSql.Indexes;

public sealed class DrillsIndex : MapIndex
{
    public string DrillContentItemId { get; set; }

    public string SkillContentItemId { get; set; }

    public bool Published { get; set; }
}

public sealed class DrillsIndexProvider : IndexProvider<ContentItem>
{
    public override void Describe(DescribeContext<ContentItem> context)
    {
        // Exclusive to content items, but not single-record: one row per selected skill.
        context.For<DrillsIndex>()
            .ExclusiveToDocumentType()
            .Map(contentItem =>
            {
                if (contentItem.ContentType != ContentTypes.Drill)
                {
                    return null;
                }

                var skillIds = contentItem
                    .GetContentPickerValues("DrillPart", "Skills")
                    .Where(id => !string.IsNullOrWhiteSpace(id))
                    .Distinct(StringComparer.Ordinal)
                    .ToArray();

                if (skillIds.Length == 0)
                {
                    return null;
                }

                return skillIds.Select(skillId => new DrillsIndex
                {
                    DrillContentItemId = contentItem.ContentItemId,
                    SkillContentItemId = skillId,
                    Published = contentItem.Published,
                });
            });
    }
}

Declaring What an Index Holds (YesSql 6.3)

A query joining a map index groups its matches by document (to return each document once) and counts distinct documents, so a page reads every match before it can be sorted. Declarations let YesSql skip that work:

| Declaration | Meaning | Effect |

| --- | --- | --- |

| .ExclusiveToDocumentType() | Only documents of the provider's type have records in the index. | A count reads the index tables without joining the Document table. |

| .SingleRecordPerDocument() | The map returns at most one record per document; saving throws if it returns more. | A query joining only single-record indexes isn't grouped, so a page stops as soon as it is full when a database index serves its order, and its count uses count(*). |

context.For<ProductIndex>()
    .ExclusiveToDocumentType()
    .SingleRecordPerDocument()
    .When(contentItem => contentItem.Has<ProductPart>())
    .Map(contentItem => new ProductIndex
    {
        ContentItemId = contentItem.ContentItemId,
        Price = contentItem.As<ProductPart>().Price,
    });

Built-in indexes declaring both: ContentItemIndex, ContainedPartIndex, LocalizedContentItemIndex, UserIndex, WorkflowIndex, DataPipelineRunIndex, AuditTrailEventIndex and NotificationIndex. A query that joins only these (for example ContentItemIndex alone) is no longer grouped by document; joining any other index, such as TaxonomyIndex or your own undeclared index, brings the grouping back.

Migration Example

using CrestApps.Sports.Calendar.Indexes;
using OrchardCore.Data.Migration;

namespace CrestApps.Sports.Calendar.Migrations;

internal sealed class SportEventMigrations : DataMigration
{
    public async Task<int> UpdateFrom1Async()
    {
        await SchemaBuilder.CreateMapIndexTableAsync<SportEventPartIndex>(table => table
            .Column<string>("ContentItemId", column => column.WithLength(26))
            .Column<bool>("Published")
            .Column<DateTime>("EventDateUtc")
            .Column<DateTime?>("EndDateUtc")
        );

        await SchemaBuilder.AlterIndexTableAsync<SportEventPartIndex>(table => table
            .CreateIndex(
                "IDX_SportEventPartIndex_EventDateUtc",
                "Published",
                "EventDateUtc")
            .CreateIndex(
                "IDX_SportEventPartIndex_EndDateUtc",
                "Published",
                "EndDateUtc")
        );

        return 2;
    }
}

DocumentId and Enum Pattern

public enum SportEventStatus
{
    Draft,
    Published,
}

public sealed class SportEventPartIndex : MapIndex
{
    public long DocumentId { get; set; }

    public string ContentItemId { get; set; }

    public SportEventStatus Status { get; set; }
}

await SchemaBuilder.CreateMapIndexTableAsync<SportEventPartIndex>(table => table
    .Column<string>("ContentItemId", column => column.WithLength(26))
    .Column<SportEventStatus>("Status")
);

Startup Registration

using CrestApps.Sports.Core.Indexes;
using CrestApps.Sports.Drills.Migrations;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Data.Migration;
using OrchardCore.Modules;
using YesSql.Indexes;

namespace CrestApps.Sports.Drills;

public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddIndexProvider<DrillsIndexProvider>();
        // DrillsMigrations creates the DrillsIndex table, as in the migration example above.
        services.AddDataMigration<DrillsMigrations>();
    }
}

Querying with QueryIndex

using CrestApps.Sports.Core.Indexes;
using YesSql;

public sealed class SportsContentService
{
    private readonly ISession _session;

    public SportsContentService(ISession session)
    {
        _session = session;
    }

    public async Task<IEnumerable<string>> GetDrillIdsBySkillAsync(string skillContentItemId)
    {
        var rows = await _session
            .QueryIndex<DrillsIndex>(x => x.Published && x.SkillContentItemId == skillContentItemId)
            .ListAsync();

        return rows.Select(x => x.DrillContentItemId);
    }
}

Exposing an Index to Data Pipelines and Reports

A MapIndex makes a good backing store for a custom data source: derive a RecordDataSet<TIndex> that pages through ISession.QueryIndex<TIndex>() in a stable order (for example by Id), and apply DataConditions.Keys(...)/DataConditions.DateRange(...) to the index query. Implement IAggregateRecordDataSet to answer counts and sums with a GROUP BY on the index table. See orchardcore-data-sources, and orchardcore-data-formulas for how pipeline filters arrive as DataConditions.

YesSql Configuration

YesSql options (command page size, query gating, identity column size, ...) are configured in the OrchardCore:YesSql section (formerly OrchardCore_YesSql, still read but deprecated in 4.0); see orchardcore-data.

Orchard Core 4.0 uses YesSql 6.3.0. Index providers, MapIndex/ReduceIndex, SchemaBuilder and QueryIndex APIs are unchanged; 6.3 adds the index declarations above, SkipDeduplication() and NoIndexOptimizations(), and creates the indexes that a data migration adds to an existing table without blocking writes (online on SQL Server editions that support it, ALGORITHM=INPLACE, LOCK=NONE on MySQL; PostgreSQL and SQLite still block). Set OrchardCore:YesSql:ConcurrentIndexCreationEnabled to false to create them the regular way. YesSql also emits telemetry: with orchardcore-opentelemetry, add YesSql to Tracing:Sources and Metrics:Meters to see a span per command, db.client.operation.duration, and the yessql.session.commands histogram that exposes N+1 query patterns. IncludeQueryTextInTelemetry (default false) adds the SQL text to those spans; raw SQL fragments passed to a query are included verbatim, so leave it off when telemetry leaves your trust boundary.

Best Practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.