0
votes

I am new to Elastic search,

I have object structure like,

 class Student
{
    int schoolId;
    List<Subject> Subjects;
}

class Subject
{
    string title;
    string type;
}

I am trying to list down all the unique Subject titles. So far, I have the following Query that works in Sense and gives me desired result.

curl -XGET "http://localhost:9200/school-v0.1/student/_search?search_type=count&routing=5" -d '{
  "filter": 
  {
     "term":  { "schoolId": 5  }
  },
  "aggs": 
  {
      "SubjectsAggr": 
      {
           "nested": { "path": "Subjects"  },
           "aggs": 
           {
               "TitlesAggr": 
               {
                    "terms": { "field": "subject.title" }
               }
           } 
       }
    }
}'

But I am not getting the NEST equivalent of the same. Refer below. Am I missing something?

  var result = this.ElasticClient.Search<Student>(q => q
                .Index(this.ElasticClient.Index)
                .Routing(schoolId)
                .SearchType(SearchType.Count)
                .Filter(q1 => q1.Term(a => a.schoolId, schoolId))
                .Aggregations(student => student.Nested("SubjectsAggr", b => b.Path("subjects")
                    .Aggregations(sub => sub.Terms("TitlesAggr", s => s.Field("subject.title"))))));

    //Below is what I hope to do, but the I get compilation errors because there seems to be something wrong with above NEST query that I have written

            var subjectsAggregation = esResult.Aggs.Nested("SubjectsAggr");
    var titlesAggregation = subjectsAggregation.Aggs.Terms("TitlesAggr");

            var subjects = new List<string>();
            foreach (var s in titlesAggregation.Items)
            {
              subjects.Add(s.Key);
            }

Could you please help me find it? Thank you.

1
.Index(this.ElasticClient.Index) seems wrong Index() expects a string or CLR Type that resolves to school-v0.1 - Martijn Laarman
That is a property in my class. So it does resolve properly. But I think there is something wrong with the way I am forming NEST aggregations. - Legolas21
Just found out that my NEST query was correct. Only the way I was trying fetch data out was not correct. Please see my answer below. Thanks. - Legolas21

1 Answers

0
votes

My NEST query was indeed correct. I was only not fetching the results out in appropriate way. I am now able to extract the needed information out of the search result as shown below.

            var subjectsAggregation = result.Aggs.Nested("SubjectsAggr");
            var titlesAggregation = subjectsAggregation.Aggregations["TitlesAggr"];
            var titlesBucket = titlesAggregation as Bucket;

            var titles = new List<string>();
            if (titlesBucket != null)
            {
                foreach (var title in titlesBucket.Items)
                {
                    titles.Add((((KeyItem) title).Key));
                }
            }