even though you could do this using a script in the terms aggregation - it would make more sense (especially when you want fast results, as the scripting solution it doing things at search time which should be done at index time), to index the first four digits of your field into a separate field.
There are a few different ways to do this during indexing by using different token filters. This example might not be the best, but works in this test...
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.