Search code examples
elasticsearchnest

Elasticsearch - How to get the sum of fields with terms?


I'm trying to get a sum of some fields, with terms (let's say, number of files of specific user with Id).

First I tried:

_mainManager.Client.Search<object>
            (q => q
            .Type("Mail")
            .Filter(c => c.Term("SentMail_Sender_Id", userId))
            .Aggregations(a => a.Terms("sum", g => g.Field("SentMail_Upload_Files_Count")))
            .Size(1));

But no luck in Agg property, so I tried this:

_mainManager.Client.Search<object>
            (q => q
            .Type("Mail")
            .Aggregations(a => a.Filter("fil", b => b.Filter(c => c.Term("SentMail_Sender_Id", userId))).Sum("sum", f => f.Field("SentMail_Upload_Files_Count"))));

But then again, no luck there. Can anyone help?


Solution

  • The following code gives you the result that you need I thing:

    PUT /mail/message/1
    {
      "SentMail_Sender_Id":1,
      "SentMail_Upload_Files_Count":10
    }
    
    PUT /mail/message/2
    {
      "SentMail_Sender_Id":1,
      "SentMail_Upload_Files_Count":2
    }
    
    PUT /mail/message/3
    {
      "SentMail_Sender_Id":2,
      "SentMail_Upload_Files_Count":7
    }
    
    GET /mail/_search?search_type=count
    {
      "query": {
        "filtered": {
          "filter": {
            "term": {
              "SentMail_Sender_Id": 1
            }
          }
        }
      },
      "aggs": {
        "total": {
          "stats": {
            "field": "SentMail_Upload_Files_Count"
          }
        }
      }
    }
    

    The response is:

    "aggregations": {
          "total": {
             "count": 2,
             "min": 2,
             "max": 10,
             "avg": 6,
             "sum": 12
          }
       }