diff --git a/Aggregation/CardinalityAggregation.php b/Aggregation/CardinalityAggregation.php
index 070f77b3faf61d160acc95825c67a67b591c6d96..36aec868229a697a497e5a7301d1700d70a957f6 100644
--- a/Aggregation/CardinalityAggregation.php
+++ b/Aggregation/CardinalityAggregation.php
@@ -30,21 +30,31 @@ class CardinalityAggregation extends AbstractAggregation
      */
     private $rehash;
 
+    /**
+     * @var string
+     */
+    private $script;
+
     /**
      * {@inheritdoc}
      */
     public function getArray()
     {
-        if (!$this->getField()) {
-            return new \stdClass();
+        $out = [];
+
+        if ($this->getField()) {
+            $out['field'] = $this->getField();
+        } elseif ($this->getScript()) {
+            $out['script'] = $this->getScript();
+        } else {
+            throw new \LogicException('Cardinality aggregation must have field or script set.');
         }
 
-        $out['field'] = $this->getField();
         if ($this->getPrecisionThreshold()) {
             $out['precision_threshold'] = $this->getPrecisionThreshold();
         }
 
-        if ($this->isRehash() !== null) {
+        if ($this->isRehash()) {
             $out['rehash'] = $this->isRehash();
         }
 
@@ -85,6 +95,22 @@ class CardinalityAggregation extends AbstractAggregation
         $this->rehash = $rehash;
     }
 
+    /**
+     * @return string
+     */
+    public function getScript()
+    {
+        return $this->script;
+    }
+
+    /**
+     * @param string $script
+     */
+    public function setScript($script)
+    {
+        $this->script = $script;
+    }
+
     /**
      * {@inheritdoc}
      */