从cosmos数据库获取最新记录的问题

时间:2017-11-23 12:57:58

标签: c# azure azure-cosmosdb

我在简单的Web应用程序上工作,因为我使用cosmos数据库将一些数据保存到其中。到目前为止一切正常。但是每当我想从宇宙数据库中获取最新的时间值时,就需要超过一分钟的时间来提供最新记录。

这是我为从cosmos数据库获取最新记录而编写的代码。

        public static async Task<IEnumerable<IoTHubDataPoint>> GetItemsAsync()
    {
        IDocumentQuery<IoTHubDataPoint> query = client.CreateDocumentQuery<IoTHubDataPoint>(
            UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),               
            new FeedOptions { MaxItemCount = 1, EnableCrossPartitionQuery = true}).OrderByDescending(x=>x.Time).Take(1)
            .AsDocumentQuery();

        List<IoTHubDataPoint> results = new List<ServiceMaxIoTHubDataPoint>();
        while (query.HasMoreResults)
        {
            results.AddRange(await Task.Run(async () => await query.ExecuteNextAsync<IoTHubDataPoint>()) );
        }
        //return results.OrderByDescending(x => x.Time).Take(1).ToArray();
        return results;

    }

这是azure cosmos数据库中的样本数据。

{
"DeviceID": "IoT-1",
"Time": "2017-11-02T14:46:06.7846161",
"Temperature": 28.63403,
"Pressure": "95089.47",
"Altitude": "532.5873",
"LightStatus": "Too Bright",
"LightCDSValue": "193",
"LightCDSVoltageValue": "0.943304",
"EventProcessedUtcTime": "2017-11-02T14:46:40.3930989Z",
"PartitionId": 0,
"EventEnqueuedUtcTime": "2017-11-02T14:46:07.6Z",
"IoTHub": {
    "MessageId": null,
    "CorrelationId": null,
    "ConnectionDeviceId": "IoT-1",
    "ConnectionDeviceGenerationId": "636449561753440920",
    "EnqueuedTime": "2017-11-02T14:46:07.826Z",
    "StreamId": null
},
"id": "XXXXXXXXXXXXXX",
"_rid": "XXXXXXXXXXXXXx",
"_self": "dbs/4RM3AA==/colls/4RM3AOJ1XQA=/docs/XXXXXXXXXXXx==/",
"_etag": "\"XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXx\"",
"_attachments": "attachments/",
"_ts": XXXXXX
}

有谁能告诉我如何解决上述问题?

1 个答案:

答案 0 :(得分:0)

这是您可以在Azure SELECT top 1 * FROM c order by c._ts desc中执行的查询