cosmos-db
  1. cosmos-db-document

CosmosDB Data Models

Introduction

CosmosDB is a flexible and scalable cloud-based NoSQL database service provided by Microsoft Azure. One of the key features of CosmosDB is its support for multiple data models, including document, key-value, graph, and column-family models. In this tutorial, we will focus on the document data model, which is similar to the JSON data format and closely related to the concept of an object in object-oriented programming.

Syntax

The syntax for creating a document in CosmosDB is:

{
    "id": "document_id",
    "property1": "value1",
    "property2": "value2",
    ...
}

where id represents the unique identifier for the document. The properties and values can be customized based on the needs of the application.

Example

Here is an example of a document in CosmosDB:

{
    "id": "1",
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipcode": "12345"
    }
}

Output

The output of a query to retrieve a document in CosmosDB typically looks like:

{
    "id": "1",
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipcode": "12345"
    },
    "_rid": "XXXXXXXXXXXXXXXXXXXXXXX",
    "_self": "dbs/XXXXXXXXXXXX/colls/XXXXXXXXXXXX/docs/XXXXXXXXXXXXXXXXXXXXXX",
    "_etag": "\"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"",
    "_attachments": "attachments/",
    "_ts": XXXXXXXXXXXXX
}

The additional fields (_rid, _self, _etag, _attachments, and _ts) provide metadata about the document.

Explanation

The document data model in CosmosDB allows developers to store and retrieve semi-structured data. This means that the data is organized into a hierarchy of objects rather than tables with predefined columns. The document format is flexible, and properties can be added or removed as needed.

CosmosDB also provides a rich query language called SQL (Structured Query Language) API, which allows developers to query data using familiar SQL syntax.

Use

The document data model is commonly used in web applications and content management systems where data is dynamic and frequently changing. It is particularly useful for scenarios where a schema-less storage approach is needed.

Important Points

  1. Documents in CosmosDB can have up to 2 MB of data.
  2. CosmosDB uses a partition key to distribute data across multiple partitions for scalable performance.
  3. Documents with different structures can be stored in the same collection.

Summary

The document data model in CosmosDB provides a flexible and scalable solution for storing semi-structured data. It allows developers to easily add, remove, and query data based on the needs of the application. CosmosDB's SQL API provides a familiar syntax for querying data, and its support for multiple data models makes it a versatile database service.

Published on: