簡體   English   中英

使用C#查詢CosmosDB文檔

[英]Query CosmosDB document using C#

我有存儲在cosmos db中的文檔,我有多個文檔用於同一“ stationkey”(分區鍵),在此示例中,stationkey“ ABC”具有多個文檔,其中“ yymm”具有“ 2018-02”和“ 2018-01” “等等,

我正在嘗試的查詢是獲取給定stationkey和yymm過濾器組合的所有“ avg”和“ dd”字段以及“ yymm”

JSON文件

我正在嘗試使用C#查詢,我正在嘗試從“數據”數組中獲取“ avg”,“ dd”和“ yymm”字段,我編寫的查詢給出了整個“數據”數組。

var weatherQuery = this.docClient.CreateDocumentQuery<WeatherStation>(docUri, queryOptions)
            .Where(wq => wq.stationName == stationKey && lstYearMonthFilter.Contains(wq.yearMonth))
            .Select(s => s.data);

從文檔數組中查詢特定字段的最佳方法是什么?

因此,您在s => s.data中獲得了數據。 要僅從數組中獲取平均值,您必須執行另一個投影,如下所示:

.Select (s => s.data.Select ( a => a.avg ))

修改我的答案,就像您說的那樣,在“數據”上找不到“選擇”。

這樣定義一個類MyDocument:

public class Datum
{
    [JsonProperty("dd")]
    public string dd;

    [JsonProperty("max")]
    public int max;

    [JsonProperty("min")]
    public int min;

    [JsonProperty("avg")]
    public int avg;
}

public class MyDocument : Document
{
    [JsonProperty("id")]
    public string id;

    [JsonProperty("data")]
    public Datum[] data;
}

相應地修改您的代碼

IDocumentQuery<MyDocument> query = client.CreateDocumentQuery<MyDocument>(UriFactory.CreateDocumentCollectionUri(_database, _collection),
            new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true, MaxDegreeOfParallelism = 199, MaxBufferedItemCount = 100000})
            .Where(predicate)
            .AsDocumentQuery();

      while (query.HasMoreResults)
        {
            FeedResponse<MyDocument> feedResponse = await query.ExecuteNextAsync<MyDocument>();
            Console.WriteLine (feedResponse.Select(x => x.data.Select(y => y.avg)));
        }

高溫超導

您可以使用雙嵌套匿名類從數組項中僅選擇特定字段-請參閱下面更改的SelectMany。 這將在每個Datum中返回yymm,因此效率可能不如選擇整個數組那么有效-在兩種情況下都必須測量RU / s。

var weatherQuery = this.docClient.CreateDocumentQuery<WeatherStation>(docUri, queryOptions)
    .Where(wq => wq.stationName == stationKey && lstYearMonthFilter.Contains(wq.yearMonth))
    .SelectMany(x => x.data.Select(y => new { x.yymm, data = new[] { new { y.dd, y.avg } } }))
    .AsDocumentQuery();

var results = new List<WeatherStation>();

while (weatherQuery.HasMoreResults)
{
    results.AddRange(await weatherQuery.ExecuteNextAsync<WeatherStation>());
}

var groupedResults = results
    .GroupBy(x => x.yymm)
    .Select(x => new { x.First().yymm, data = x.SelectMany(y => y.data).ToArray() })
    .Select(x => new WeatherStation() { yymm = x.yymm, data = x.data });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM