0

Is there a way to get a total results count when calling Aggregate function?

Note that I'm not using Aggregate function to aggregate results, but as an advanced search query, because Search function does not allow to sort by multiple fields.

RediSearch returns total documents matched count, but I can't find a way to get this number using NRediSearch library.

zigzag
  • 579
  • 5
  • 17

1 Answers1

1

With NRediSearch

Using NRediSearch, you would need to build and execute aggregation that will run a GROUPBY 0 and the COUNT reducer, say you have a person-idx index and you want to count all the Person documents in Redis:

var client = new Client("person-idx", muxer.GetDatabase());
var result = await client.AggregateAsync(new AggregationBuilder().GroupBy(new List<string>(), new List<Reducer>{Reducers.Count()}));
Console.WriteLine(result.GetResults().First().Values.First());

Will get the count you are looking for.

With Redis.OM

There's a newer library Redis.OM which you can also use to make these aggregations a bit simpler, the same operation would be done with the following:

var peopleAggregations = provider.AggregationSet<Person>();
Console.WriteLine(peopleAggregations.Count());
slorello
  • 901
  • 5
  • 6
  • The thing is that I don't want to run a second aggregation, just to get results count of the first aggregation query. I had to modify source of AggregationResult class to read the total count value. Since AggregationResult currently ignores returned results count, it is impossible to get the count without modifying the source. So a second query is a valid in that case. That Redis.OM library looks interesting indeed. – zigzag Dec 08 '21 at 10:45
  • Ahh gotcha, could you modify the question with the aggregation you are trying to run and get a count on? – slorello Dec 08 '21 at 12:56
  • Relevant part of the query: `agg.SortBy(new SortedField[] { new("@price", Order.Ascending), new("@distance", Order.Ascending) })`. Aggregation query returns first 10 items & total items count. – zigzag Dec 08 '21 at 14:06
  • Are you trying to pull back all the records and just looking for the count of records that you need to pull back? If so, I wouldn't bother looking at the count, I'd just use the Cursor Pagination - see this [repo](https://github.com/slorello89/pagination-nredisearch/blob/main/Program.cs#L55) where I build an example with NRediSearch using cursor pagination. If you really do just need the count, then yeah run the Count reducer. – slorello Dec 08 '21 at 15:03
  • No, just first 10 results (with pagination to load more if requested) + total results count. AggregationResult in JRediSearch contains totalResults property, but it's missing in NRediSearch. – zigzag Dec 08 '21 at 15:47