# NEST C# aggregations - Count and Max

**URL:** https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171
**Category:** Elasticsearch
**Tags:** language-clients
**Created:** [July 7, 2020, 1:42pm UTC](https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171 "2020-07-07T13:42:17Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![rd8388](https://avatars.discourse-cdn.com/v4/letter/r/c6cbf5/32.png) [@rd8388](https://discuss.elastic.co/u/rd8388)
#### Post date: [July 7, 2020, 1:42pm UTC](https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171/1 "2020-07-07T13:42:17Z")

</div>

```auto
var sDescriptor = new Nest.SearchDescriptor<MyRecordType>();
sDescriptor.Aggregations(a =>a.Terms("sources", t => t.Field(f => f.sourceName.Suffix("keyword"))));
var searchResponse = _client.Search<MyRecordType>(sDescriptor);

```

gives me a bucket containing a count of the record grouped by "sourceName".

```auto
var sDescriptor = new Nest.SearchDescriptor<MyRecordType>();
sDescriptor.Aggregations(a => a.Max("last_upserted", m => m.Field(p => p.recordUpserted))
var searchResponse = _client.Search<MyRecordType>(sDescriptor);

```

gives the max value for recordUpserted across the entire index.

How do I combine the two please to get a count of records per source and the value of the most recently upserted record for each source?

MS SQL example of what I would like to achieve...

```auto
SELECT SourceName, COUNT(1) AS NumRecords, MAX(UpsertedDate) AS MostRecentUpdate
FROM MyTable
GROUP BY [SourceName]

```

---

<div class="post-metadata">

### Author: ![rd8388](https://avatars.discourse-cdn.com/v4/letter/r/c6cbf5/32.png) [@rd8388](https://discuss.elastic.co/u/rd8388)
#### Post date: [July 8, 2020, 11:10am UTC](https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171/2 "2020-07-08T11:10:26Z")

</div>

Inspired by legacy documentation... [https://www.elastic.co/guide/en/elasticsearch/client/net-api/1.x/handling-aggregations.html](https://www.elastic.co/guide/en/elasticsearch/client/net-api/1.x/handling-aggregations.html)

The the (slightly smelly) code below is working and will suffice for now.

```auto
List<DataSourceInfo> dsi = new List<DataSourceInfo>();
var result = _client.Search<MyRecordType>(s => s
    .Aggregations(a => a.Terms("sources", t =>
                 t.Field(f => f.sourceName.Suffix("keyword"))
    .Aggregations(aa => aa.Max("last_updated", m =>
                 m.Field(f => f.recordUpserted))))));
var sources = result.Aggregations.Terms<string>("sources");
foreach (var item in sources.Buckets) {
    var valueAgg = item.Values.FirstOrDefault() as Nest.ValueAggregate;
    string maxUpsert = DateTime.Parse(valueAgg.ValueAsString).ToString("dd/MM/yyyy HH:mm");                  
    dsi.Add(new DataSourceInfo() {
        SourceName = item.Key,
        NumRecords = (int)item.DocCount,
        MaxUpsert = maxUpsert
    });
}

```

---

<div class="post-metadata">

### Author: ![forloop](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/forloop/32/9021_2.png) [@forloop](https://discuss.elastic.co/u/forloop)
#### Post date: [July 13, 2020, 11:40pm UTC](https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171/3 "2020-07-13T23:40:18Z")

</div>

Each bucket in the terms aggregation exposes the helper methods to retrieve a sub aggregation by name, so a slightly cleaner way would be

```auto
var searchResponse = client.Search<MyRecordType>(s => s
	.Size(0)
	.Aggregations(a => a
		.Terms("sources", t => t
			.Field(f => f.sourceName.Suffix("keyword"))
			.Aggregations(aa => aa
				.Max("last_updated", m => m
					.Field(f => f.recordUpserted)
				)
			)
		)
	)
);

var sources = searchResponse.Aggregations.Terms<string>("sources");
foreach (var bucket in sources.Buckets)
{
	var valueAgg = bucket.Max("last_updated");
	string maxUpsert = valueAgg.ValueAsString;
}

```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [August 10, 2020, 11:49pm UTC](https://discuss.elastic.co/t/nest-c-aggregations-count-and-max/240171/4 "2020-08-10T23:49:16Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
