Home > Back-end >  How can I order by multiple columns using the IQueryable in Cosmos DB?
How can I order by multiple columns using the IQueryable in Cosmos DB?

Time:11-20

How can I order by multiple columns using the IQueryable in Cosmos DB?

I tried to do the following:

books.OrderBy(book => book.Author).ThenBy(book => book.Name);

and it works on the Cosmos DB simulator, but it does not work on a real DB. Why?

Here is the error I am getting:

The order by query does not have a corresponding composite index that it can be served from.

CodePudding user response:

This isn't an issue with your C# code. If you want to use ORDER BY on a property that property needs to be indexed. For multiple columns it's the same although you need a composite index for all the properties that appear in your ORDER BY clause in the exact same order.

For your use case you would need the following index added to your Cosmos DB container:

"compositeIndexes": [
    [
        {
            "path": "/Author",
            "order": "ascending"
        },
        {
            "path": "/Name",
            "order": "ascending"
        }
    ]
]
  • Related