首页 文章

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

提问于
浏览
2

我的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的大部分信息 . All documents in my DocumentDB collection are actually JSON serialized version of FatDocument .

出于我的业务应用程序中的许多目的,我不需要检索FatProperty . In order to save some RUs ,我创建了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> .

如果我使用 client.CreateDocumentQuery<LightDocument> 创建 QueryDocument ,则执行后,此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 .

Note: 反转AsEnumerable而Where这里不是一个选项 . 我们希望将 where 子句转换为DocumentDB where子句 .

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

1 回答

  • 6

    如果使用LINQ而不是SQL查询,则可以使用IQueriable上的.Select()方法将fat文档投影到light文档 . 然后,您可以将结果链接到.Where()方法 .

    Light Document Query

    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();
    

    Light Document Result

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

    Fat Document Query

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

    Fat Document Result

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

    轻量级文档示例中的结果查询不引用FatProperty,因此不会通过网络发送 . 我继续检查每个请求类型的RU,它们几乎是偶数,FatDocument查询的成本略高,这是合理的,因为使用的带宽更多 .

    • LightDocument查询RU:3.05

    • FatDocument查询RU:3.09

相关问题