Search code examples
azure-cosmosdb

Azure NoSQL cosmosdb schema validation/locking


We are creating .Net core 7 based CRUD operation apis. database is Azure NoSQL cosmos db. We are using CosmosClient.

Our apis are stable now.

We want to ensure that any new changes in api's do not impact existing schema. We are willing to lock existing schema. All records in container have same schema. Can we LOCK the schema? so new api's changes cannot change db record schema even accidently.


Solution

  • Not by the service. Cosmos DB is schema-less.

    You can however, on the client-side, introduce schema validation as part of your application code.

    Example handler you can use with the CosmosClient: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/Handlers/SchemaValidationHandler.cs

    It let's you define an schema:

    var myContainerSchema = JSchema.Parse(@"{
      'type': 'object',
      'properties': {
        'name': {'type': 'string'}
      },
      'required': ['name']
    }");
    

    And you can add it to the CosmosClientOptions.CustomHandlers:

    CosmosClientOptions options = new();
    //set other options
    options.CustomHandlers.Add(new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema)));