DocumentDb DocumentClient get first 25 documents

653 Views Asked by At

Getting started with Cosmos and document db/sql. Why does this not work? No error is thrown, that I can see. There is data that should return.

    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;
    }
2

There are 2 best solutions below

2
On BEST ANSWER

MaxItemCount is the maximum number of items you will get pack per enumeration operation. It doesn't return the first 25 documents but rather all the documents that match this query in aggregated batches of 25 documents per enumeration.

If you want the top 25 items your code should look like this:

[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;
}

Depending on how you index strings in your collection you may also need to set the EnableScanInQuery property of the FeedOptions object to true.

0
On

To get the top documents as you wanted, using LINQ .Take() is the right way, as Nick mentioned.

Using FeedOptions.MaxItemCount and ExecuteNextAsync is also an alternative. However it may return 0 results as you've observed so that needs to be taken into account. For more details on this, please refer to Aravind's comment on this related question: ExecuteNextAsync Not Working.