【问题标题】:DocumentDb DocumentClient get first 25 documentsDocumentDb DocumentClient 获取前 25 个文档
【发布时间】:2018-09-23 12:30:32
【问题描述】:

开始使用 Cosmos 和文档 db/sql。为什么这不起作用?没有错误被抛出,我可以看到。有应该返回的数据。

    private const string EndpointUri = "some url";
    private const string PrimaryKey = "somekey";
    private const string DbId = "People";
    private const string CollectionId = "Person";
    private DocumentClient client;

    // GET: api/Person
    [HttpGet]
    public IEnumerable<Person> Get()
    {
        this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
        FeedOptions queryOptions = new FeedOptions { MaxItemCount = 25, EnableCrossPartitionQuery = true };



        IQueryable<Person> personQuery = this.client.CreateDocumentQuery<Person>(
            UriFactory.CreateDocumentCollectionUri(DbId, CollectionId), queryOptions)
            .Where(f => f.NameFirst != "Andersen");

        List<Person> retVal = new List<Person>();
        retVal = personQuery.ToList();
        return retVal;
    }

【问题讨论】:

    标签: c# azure azure-cosmosdb documentclient


    【解决方案1】:

    MaxItemCount 是每次枚举操作您将获得的最大项目数。它不会返回前 25 个文档,而是返回与此查询匹配的所有文档,每次枚举 25 个文档的聚合批次。

    如果您想要前 25 项,您的代码应如下所示:

    [HttpGet]
    public async Task<IEnumerable<Person>> Get()
    {
        this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
        FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true };
    
        var personQuery = this.client.CreateDocumentQuery<Person>(
            UriFactory.CreateDocumentCollectionUri(DbId, CollectionId), queryOptions)
            .Where(f => f.NameFirst != "Andersen").Take(25).AsDocumentQuery();
    
        List<Person> retVal = new List<Person>();
    
        while(personQuery.HasMoreResults)
        {
            var results = await personQuery.ExecuteNextAsync<Person>();
            retVal.AddRange(results);
        }
    
        return retVal;
    }
    

    根据您在集合中索引字符串的方式,您可能还需要将FeedOptions 对象的EnableScanInQuery 属性设置为true

    【讨论】:

    • 这似乎不起作用。严重性代码描述项目文件行抑制状态错误 CS1503 参数 1:无法从 'Microsoft.Azure.Documents.Client.FeedResponse' 转换为 'System.Collections.Generic.IEnumerable' CoreWebApp \documents \visual studio 2017\Projects\CoreWebApp\CoreWebApp\Api\PersonController.cs 44 活动
    • @WouldRatherBuildAMotor 我在ExecuteNextAsync 上添加了映射类型。试试更新的答案。
    【解决方案2】:

    正如尼克所说,要获得所需的顶级文档,使用 LINQ .Take() 是正确的方法。

    使用 FeedOptions.MaxItemCount 和 ExecuteNextAsync 也是一种替代方法。但是,正如您所观察到的,它可能会返回 0 个结果,因此需要考虑到这一点。有关这方面的更多详细信息,请参阅 Aravind 对此相关问题的评论:ExecuteNextAsync Not Working

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多