2016-11-28 28 views
1

我有一個用於DocumentDB文檔的.NET POCO類。使用.NET DocumentDB SDK查詢對象屬性

public class FatDocument{ 
    public string id { get; set; } 

    public string LightProperty { get;set;} 
    public string LightProperty2 { get;set;} 

    public string FatProperty { get;set;}  
} 

顧名思義,FatProperty包含Document的大部分信息。 我的DocumentDB集合中的所有文檔實際上是FatDocument的JSON序列化版本。

對於我的業務應用程序中的很多目的,我不需要檢索FatProperty。 爲了節省一些RU,我創建了一個POCO的輕型版本。

public class LightDocument{ 
    public string id { get; set; } 

    public string LightProperty { get;set;} 
    public string LightProperty2 { get;set;} 
} 

public class FatDocument: LightDocument{ 
    public string FatProperty { get;set;} 
} 

現在我正在尋找一種方法來檢索IQueryable<LightDocument>

如果我創建一個QueryDocumentclient.CreateDocumentQuery<LightDocument>,執行後,此IQueryable返回一個LightDocument枚舉。但在DocumentDB請求檢查之後,我們看到一個SELECT * FROM。這不是我們正在尋找的,我們希望忽略DocumentDB查詢中的FatProperty以保存一些RU(並在客戶端應用程序和DocumentDB之間請求有效載荷)。

我也嘗試過使用SQL語法

var queryspec = new SqlQuerySpec() { QueryText = "SELECT c.id, c.LightProperty, c.LightProperty2"}; 
var queryable = client.CreateDocumentQuery<LightDocument>(GetDocUri(), queryspec); 
queryable.Where(c => /* Some filtering logic */); 
queryable.AsEnumerable(); //EXCEPTION thrown 

這將引發異常Method 'AsSQL' is not supported. Only LINQ Methods are supported結合查詢的創建。

注意:反相AsEnumerable和Where不是一個選項在這裏。我們希望將where子句翻譯成DocumentDB where子句。

我的問題是:如何用DocumentDB .NET SDK創建返回部分文檔的LINQ查詢?

+1

JamyRyals有這個最佳的解決方案 - 通過使用投影選擇。我還建議檢查一下這個變化是否對RU有重大改變。一般來說,附加屬性的投影不會在RU中造成很大的差異。 –

+1

根據請求單元,我獲得了x2增益! –

回答

5

如果您使用LINQ而不是SQL查詢,則可以使用IQueriable上的.Select()方法將胖文檔投影到輕文檔。然後,您可以將結果鏈接到.Where()方法。

光文獻查詢

var lightDocumentQuery = client.CreateDocumentQuery<LightDocument>(GetCollectionLink()) 
           .Select(d => new LightDocument { id = d.id, LightProperty = d.LightProperty, LightProperty2 = d.LightProperty2 }) 
           .Where(d => d.LightProperty == compareTo) 
           .AsDocumentQuery(); 

光文獻結果

{ 
    "id": "9d4ec687-95a5-68df-d51d-5d2fb0143231", 
    "LightProperty": "someValue", 
    "LightProperty2": "someOtherValue" 
} 

脂肪文獻查詢

var fatDocumentQuery = client.CreateDocumentQuery<FatDocument>(GetCollectionLink()) 
          .Where(d => d.LightProperty == compareTo) 
          .AsDocumentQuery(); 

脂肪文獻結果

{ 
    "FatProperty": "SomeFatProperty usually json", 
    "id": "9d4ec687-95a5-68df-d51d-5d2fb0143231", 
    "LightProperty": "someValue", 
    "LightProperty2": "someOtherValue" 
} 

在光文件的例子所得的查詢不引用FatProperty以便它不通過網絡發送。我繼續檢查每個請求類型的RU,並且它們幾乎是均勻的,FatDocument查詢的成本略高一些,這是合理的,因爲有更多的帶寬被使用。

  • LightDocument Query RU:3。05
  • FatDocument查詢RU:3.09
+1

實際上,您需要重新創建「燈光實體」才能進行選擇工作。我試過'Select(d =>(LightDocument)d)',但它不起作用。您需要在.Select語句中重新創建對象'.Select(c => new LightDocument(){/ * Copy properties * /}' –

+0

已更新,以表明謝謝 – JamyRyals

+0

爲簡化示例,我的情況是,通過丟棄一個擁有自己的索引的「富有」對象的胖財產,而不僅僅是一個普通的舊字符串,我在RU中獲得了一些非常顯着的收益 –