使用.NET DocumentDB SDK查询对象属性

时间:2016-11-28 13:25:13

标签: c# linq azure-cosmosdb

我的DocumentDB文档有一个.NET POCO类。

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。 为了节省一些R ,我创建了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>

如果我使用QueryDocument创建client.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子句转换为DocumentDB where子句。

我的问题是:如何使用DocumentDB .NET SDK返回部分文档来创建LINQ查询?

1 个答案:

答案 0 :(得分:6)

如果您使用的是LINQ而不是SQL查询,则可以使用IQueriable上的.Select()方法将fat文档投影到light文档。然后,您可以将结果链接到.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 Query RU:3.09