Reverse Nested Aggregation Usageedit

Fluent DSL exampleedit

s => s
.Aggregations(a => a
    .Nested("tags", n => n
        .Path(p => p.Tags)
        .Aggregations(aa => aa
            .Terms("tag_names", t => t
                .Field(p => p.Tags.Suffix("name"))
                .Aggregations(aaa => aaa
                    .ReverseNested("tags_to_project", r => r
                        .Aggregations(aaaa => aaaa
                            .Terms("top_projects_per_tag", tt => tt
                                .Field(p => p.Name)
                            )
                        )
                    )
                )
            )
        )
    )
)

Object Initializer syntax exampleedit

new SearchRequest<Project>
{
    Aggregations = new NestedAggregation("tags")
    {
        Path = "tags",
        Aggregations = new TermsAggregation("tag_names")
        {
            Field = "tags.name",
            Aggregations = new ReverseNestedAggregation("tags_to_project")
            {
                Aggregations = new TermsAggregation("top_projects_per_tag")
                {
                    Field = Field<Project>(p => p.Name)
                }
            }
        }
    }
}

Example json output.

{
  "aggs": {
    "tags": {
      "nested": {
        "path": "tags"
      },
      "aggs": {
        "tag_names": {
          "terms": {
            "field": "tags.name"
          },
          "aggs": {
            "tags_to_project": {
              "reverse_nested": {},
              "aggs": {
                "top_projects_per_tag": {
                  "terms": {
                    "field": "name"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Handling Responsesedit

response.ShouldBeValid();
var tags = response.Aggs.Nested("tags");
tags.Should().NotBeNull();
var tagNames = tags.Terms("tag_names");
tagNames.Should().NotBeNull();
foreach(var tagName in tagNames.Buckets)
{
    tagName.Key.Should().NotBeNullOrEmpty();
    tagName.DocCount.Should().BeGreaterThan(0);
    var tagsToProjects = tagName.ReverseNested("tags_to_project");
    tagsToProjects.Should().NotBeNull();
    var topProjectsPerTag = tagsToProjects.Terms("top_projects_per_tag");
    topProjectsPerTag.Should().NotBeNull();
    foreach(var topProject in topProjectsPerTag.Buckets)
    {
        topProject.Key.Should().NotBeNullOrEmpty();
        topProject.DocCount.Should().BeGreaterThan(0);
    }
}