By default, the CosmosDB SDK serializes DateTime values as ISO 8601 string. So, that’s a problem if you want to execute ranges or ORDER BY queries based on DateTime properties, because by default Cosmos DB engine creates HASH-based indexes for string values.

See below:

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                },
                {
                    "kind": "Hash",
                    "dataType": "String",
                    "precision": 3
                }
            ]
        }
    ],
    "excludedPaths": []
}

To be able execute range-based queries against datetime values represented as a string need to configure index policies. Let’s go through the example.

public class Transaction
{
    public Guid Id { get; set; }
    ...
    public DateTime InvoiceDate { get; set; }
}

Index configuration must be the following:


{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/InvoiceDate/?",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                }
            ]
        }
    ],
    "excludedPaths": [
        {
            "path": "/"
        }
    ]
}

The section excludePaths means that we exclude all properties from indexing and then include InvoiceDate for indexing. More general is overlapped by more specific.

This example also shows how we can exclude properties from indexing, as by default all properties are considered for building reverse index structure. If you want to improve write operations, this approach is a first what you need to apply.

For detailed information you can go through the next pages: