如何编写Cosmos DB的SQL查询?

时间:2018-10-26 07:17:14

标签: .net azure-cosmosdb

我是Cosmos DB的新手,我有一个问题,我在Cosmos DB中创建了一个名为Student的集合,并在.net sdk中连接了该db,然后如何编写查询以从中选择所有数据。收集学生?

2 个答案:

答案 0 :(得分:0)

请参考示例代码:

class QuerySample
    {
        private static readonly string endpointUrl = "https://***.documents.azure.com:443/";
        private static readonly string authorizationKey = "***";
        private static readonly string databaseId = "db";
        private static readonly string collectionId = "coll";

        private static DocumentClient client;

        public static async void QueryTest()

        {
            client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
            var uri = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);

            var query = client.CreateDocumentQuery( uri, "select * from c",
            new FeedOptions
            {
                MaxItemCount = -1,                    
                //EnableCrossPartitionQuery = true
            });
            var queryAll = query.AsDocumentQuery();

            var results = new List<Student>();

        }
    }

希望它对您有帮助。

答案 1 :(得分:0)

有多种方法可以通过C#代码执行SQL查询。

使用.NET SDK:

private async Task<List<Student>> GetStudentsAsync()
{
    var serviceEndpoint = new Uri("https://localhost:8081");
    var masterKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
    var collectionUri = UriFactory.CreateDocumentCollectionUri("databaseId", "collectionId");
    var documentClient = new DocumentClient(serviceEndpoint, masterKey);

    var query = documentClient.CreateDocumentQuery(collectionUri, "select * from c").AsDocumentQuery();
    var results = new List<Student>();

    while (query.HasMoreResults)
    {
        results.AddRange(await query.ExecuteNextAsync<Student>());
    }

    return results;
}

还有一个我创建的库,它简化了数据访问和名为Cosmonaut的CosmosDB查询。

使用相同的东西变成这样:

private async Task<List<Student>> GetStudentsCosmonautAsync()
{
    var serviceEndpoint = new Uri("https://localhost:8081");
    var masterKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
    var databaseId = "databaseId";
    var studentStore = new CosmosStore<Student>(new CosmosStoreSettings(databaseId, serviceEndpoint, masterKey));

    return await studentStore.Query("select * from c").ToListAsync();
}

这取决于个人喜好,因此我提供了两个选项供您选择。