Get actual count of matches in Azure Search

2019-08-22 10:19发布

问题:

Azure Search returns a maximum of 1,000 results at a time. For paging on the client, I want the total count of matches in order to be able to display the correct number of paging buttons at the bottom and in order to be able to tell the user how many results there are. However, if there are over a thousand, how do I get the actual count? All I know is that there were at least 1,000 matches.

I need to be able to do this from within the SDK.

回答1:

If you want to get total number of documents in an index, one thing you could do is set IncludeTotalResultCount to true in your search parameters. Once you do that when you execute the query, you will see the count of total documents in an index in Count property of search results.

Here's a sample code for that:

        var credentials = new SearchCredentials("account-key (query or admin key)");
        var indexClient = new SearchIndexClient("account-name", "index-name", credentials);
        var searchParameters = new SearchParameters()
        {
            QueryType = QueryType.Full,
            IncludeTotalResultCount = true
        };
        var searchResults = await indexClient.Documents.SearchAsync("*", searchParameters);
        Console.WriteLine("Total documents in index (approx) = " + searchResults.Count.GetValueOrDefault());//Prints the total number of documents in the index

Please note that:

  • This count will be approximate.
  • Getting the count is an expensive operation so you should only do it with the very first request when implementing pagination.