PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] How to group by month in Elastic search

 October 25, 2022     elasticsearch, elasticsearch-5, elasticsearch-6, elasticsearch-aggregation     No comments   

Issue

I am using elastic search version 6.0.0 for group by month, I am using date histogram aggregation. example which I've tried :

{  
   "from":0,
   "size":2000,
   "_source":{  
      "includes":[  
         "cost",
         "date"
      ],
      "excludes":[  

      ],
      "aggregations":{  
         "date_hist_agg":{  
            "date_histogram":{  
               "field":"date",
               "interval":"month",
               "format":"M",
               "order":{  
                  "_key":"asc"
               },
               "min_doc_count":1
            },
            "aggregations":{  
               "cost":{  
                  "sum":{  
                     "field":"cost"
                  }
               }
            }
         }
      }
   }
}

and as a result i got 1(Jan/January) multiple times. As I have data of January-2016 ,January-2017 , January-2018 so will return 3 times January. but i Want January only once which contains the sum of All years of January.


Solution

Instead of using a date_histogram aggregation you could use a terms aggregation with a script that extracts the month from the date.

{
  "from": 0,
  "size": 2000,
  "_source": {"includes": ["cost","date"],"excludes"[]},
  "aggregations": {
    "date_hist_agg": {
      "terms": {
        "script": "doc['date'].date.monthOfYear",
        "order": {
          "_key": "asc"
        },
        "min_doc_count": 1
      },
      "aggregations": {
        "cost": {
          "sum": {
            "field": "cost"
          }
        }
      }
    }
  }
}

Note that using scripting is not optimal, if you know you'll need the month information, just create another field with that information so you can use a simple terms aggregation on it without having to use scripting.



Answered By - Val
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing