A script to delete all Entities of a given type in Sitecore Content Hub

Introduction

I found myself needing to perform a mass delete in Content Hub across multiple projects, and I thought it would be helpful to share my approach. The concept is simple: locate and delete all entities that meet specific criteria.

The following script will find all M.Asset entities created by a specified user and delete them one by one. You are welcome to reuse or modify this script to suit your needs.

The script also includes basic logging functionality as an example. Feel free to customize the logging based on your requirements. For more information on script logging, refer to the Sitecore documentation.

Prerequisites

  • Familiarity with Sitecore Content Hub
  • Access to Content Hub and the ability to execute scripts

Please refer to the Sitecore documentation for more information on how to create, manage, and execute scripts in Content Hub.

Content Hub Script (C#)

using System.Linq;
using System;
using System.Collections.Generic;
using Stylelabs.M.Base.Querying;
using Stylelabs.M.Base.Querying.Linq;
                            
try
{
    MClient.Logger.Info($"Started deleting all assets at {DateTime.Now}");
    
    var query = Query.CreateQuery(entities =>
                            from e in entities
                            where (e.DefinitionName == "M.Asset" && e.CreatedByUsername == "sergey.yatsenko@xcentium.com")
                            select e);

    var results = new List<long>();
    //Deal with very large result sets (over 50 for OOTB queries and over 10000 for iterators)
    var scroller = MClient.Querying.CreateEntityIdScroller(query, TimeSpan.FromSeconds(30));
    while (await scroller.MoveNextAsync().ConfigureAwait(false))
    {
        var ids = scroller.Current.Items;
        if (ids != null && ids.Any())
        {
            results.AddRange(ids);
        }
    }
    int counter = 0;
    if (results != null && results.Any())
    {
        MClient.Logger.Info($"Found entities. Count: {results.Count}");
        foreach(var entityId in results)
        {
            await MClient.Entities.DeleteAsync(entityId);
            if(++counter >= 1000)
            {
                MClient.Logger.Info($"Deleted 1000 assets at {DateTime.Now}");
                counter = 0;
            }
        }
    }
    
    MClient.Logger.Info($"Finished deleting all assets at {DateTime.Now}");
}
catch (Exception ex)
{
    //Log and re-throw the exception
    MClient.Logger.Error($"error message: {ex.Message}");
    throw;
}