Improve composition on koral results

Change-Id: I4877c85b4bf4a3e5f3ccdab4b8958478445679d4
diff --git a/lib/Krawfish/Compile.pm b/lib/Krawfish/Compile.pm
index 4776240..28e0548 100644
--- a/lib/Krawfish/Compile.pm
+++ b/lib/Krawfish/Compile.pm
@@ -78,7 +78,40 @@
 
 # Override to compile data
 sub compile {
-  $_[0];
+  my $self = shift;
+
+  if (DEBUG) {
+    print_log('compile', 'Compile aggregation');
+  };
+
+  # Get result object
+  my $result = $self->result;
+
+  # Add all results
+  while ($self->next) {
+    if (DEBUG) {
+      print_log(
+        'compile',
+        'Add match ' . $self->current_match->to_string
+      );
+    };
+
+    $result->add_match($self->current_match);
+  };
+
+  # Collect more data
+  my $query = $self->{query};
+  if ($query->isa('Krawfish::Compile')) {
+    $query->result($result)->compile;
+  };
+
+  if (DEBUG) {
+    print_log(
+      'compile',
+      'Result is ' . $result
+    );
+  };
+  return $result;
 };
 
 
diff --git a/lib/Krawfish/Corpus.pm b/lib/Krawfish/Corpus.pm
index 2a7c5c5..54f41e0 100644
--- a/lib/Krawfish/Corpus.pm
+++ b/lib/Krawfish/Corpus.pm
@@ -1,5 +1,9 @@
 package Krawfish::Corpus;
+use strict;
+use warnings;
 use Role::Tiny;
+use Krawfish::Log;
+
 requires qw/current
             next
             next_doc
@@ -9,9 +13,6 @@
             max_freq
             to_string
            /;
-use Krawfish::Log;
-use strict;
-use warnings;
 
 # Krawfish::Corpus is the base class for all corpus queries.
 
diff --git a/lib/Krawfish/Corpus/And.pm b/lib/Krawfish/Corpus/And.pm
index 8e3ff79..db31a89 100644
--- a/lib/Krawfish/Corpus/And.pm
+++ b/lib/Krawfish/Corpus/And.pm
@@ -1,11 +1,12 @@
 package Krawfish::Corpus::And;
+use strict;
+use warnings;
 use Role::Tiny::With;
-with 'Krawfish::Corpus';
 use List::Util qw/min/;
 use Scalar::Util qw/refaddr/;
 use Krawfish::Log;
-use strict;
-use warnings;
+
+with 'Krawfish::Corpus';
 
 # TODO:
 #   Support class flags
diff --git a/lib/Krawfish/Corpus/AndNot.pm b/lib/Krawfish/Corpus/AndNot.pm
index 92d9bdf..6f30c2b 100644
--- a/lib/Krawfish/Corpus/AndNot.pm
+++ b/lib/Krawfish/Corpus/AndNot.pm
@@ -1,9 +1,10 @@
 package Krawfish::Corpus::AndNot;
-use Role::Tiny::With;
-with 'Krawfish::Corpus';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Corpus';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Corpus/Anywhere.pm b/lib/Krawfish/Corpus/Anywhere.pm
index a3e8bec..cc7bcb4 100644
--- a/lib/Krawfish/Corpus/Anywhere.pm
+++ b/lib/Krawfish/Corpus/Anywhere.pm
@@ -1,13 +1,14 @@
 package Krawfish::Corpus::Anywhere;
+use strict;
+use warnings;
 use Role::Tiny;
-with 'Krawfish::Corpus';
 use Krawfish::Index::PostingsLive;
 use Krawfish::Posting;
 use Krawfish::Query::Nowhere;
 use Scalar::Util qw/refaddr/;
 use Krawfish::Log;
-use strict;
-use warnings;
+
+with 'Krawfish::Corpus';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Corpus/Cache.pm b/lib/Krawfish/Corpus/Cache.pm
index f4e01cb..556f43c 100644
--- a/lib/Krawfish/Corpus/Cache.pm
+++ b/lib/Krawfish/Corpus/Cache.pm
@@ -1,10 +1,11 @@
 package Krawfish::Corpus::Cache;
-use Role::Tiny;
-with 'Krawfish::Corpus';
-use Krawfish::Index::Stream;
-use Krawfish::Cache;
 use strict;
 use warnings;
+use Role::Tiny;
+use Krawfish::Index::Stream;
+use Krawfish::Cache;
+
+with 'Krawfish::Corpus';
 
 # Caching is not always a good thing. Caching is only applyable
 # to certain subqueries, caching may slow down the queries, when the
diff --git a/lib/Krawfish/Corpus/Class.pm b/lib/Krawfish/Corpus/Class.pm
index 285eafa..2ef7363 100644
--- a/lib/Krawfish/Corpus/Class.pm
+++ b/lib/Krawfish/Corpus/Class.pm
@@ -1,10 +1,11 @@
 package Krawfish::Corpus::Class;
-use Role::Tiny;
-with 'Krawfish::Corpus';
-use Krawfish::Util::Bits qw/classes_to_flags bitstring/;
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny;
+use Krawfish::Util::Bits qw/classes_to_flags bitstring/;
+use Krawfish::Log;
+
+with 'Krawfish::Corpus';
 
 # "class" queries are useful with "or" queries.
 # They return the information, if a match
diff --git a/lib/Krawfish/Corpus/Distribution.pm b/lib/Krawfish/Corpus/Distribution.pm
index 27e8889..6120a1a 100644
--- a/lib/Krawfish/Corpus/Distribution.pm
+++ b/lib/Krawfish/Corpus/Distribution.pm
@@ -1,8 +1,9 @@
 package Krawfish::Corpus::Distribution;
-use Role::Tiny;
-with 'Krawfish::Corpus';
 use strict;
 use warnings;
+use Role::Tiny;
+
+with 'Krawfish::Corpus';
 
 # TODO:
 #   distr([1:3], 'author:Goethe', 'author:Schiller')
diff --git a/lib/Krawfish/Corpus/DocVector.pm b/lib/Krawfish/Corpus/DocVector.pm
index 4096f5b..e0a9fdc 100644
--- a/lib/Krawfish/Corpus/DocVector.pm
+++ b/lib/Krawfish/Corpus/DocVector.pm
@@ -1,8 +1,9 @@
 package Krawfish::Corpus::DocVector;
-use Role::Tiny;
-with 'Krawfish::Corpus';
 use strict;
 use warnings;
+use Role::Tiny;
+
+with 'Krawfish::Corpus';
 
 # Accepts a vector of UIDs, that are translated
 # to a sorted vector of document IDs to be used in
diff --git a/lib/Krawfish/Corpus/FieldID.pm b/lib/Krawfish/Corpus/FieldID.pm
index 9747e81..eb381af 100644
--- a/lib/Krawfish/Corpus/FieldID.pm
+++ b/lib/Krawfish/Corpus/FieldID.pm
@@ -1,11 +1,12 @@
 package Krawfish::Corpus::FieldID;
+use strict;
+use warnings;
 use Role::Tiny::With;
-with 'Krawfish::Corpus';
 use Krawfish::Posting;
 use Krawfish::Query::Nowhere;
 use Krawfish::Log;
-use strict;
-use warnings;
+
+with 'Krawfish::Corpus';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Corpus/Or.pm b/lib/Krawfish/Corpus/Or.pm
index dfb8e0a..ddf80bf 100644
--- a/lib/Krawfish/Corpus/Or.pm
+++ b/lib/Krawfish/Corpus/Or.pm
@@ -1,10 +1,11 @@
 package Krawfish::Corpus::Or;
-use Role::Tiny::With;
-with 'Krawfish::Corpus';
-use Krawfish::Util::Bits;
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Util::Bits;
+use Krawfish::Log;
+
+with 'Krawfish::Corpus';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Corpus/Span.pm b/lib/Krawfish/Corpus/Span.pm
index 7a2455a..5ee368b 100644
--- a/lib/Krawfish/Corpus/Span.pm
+++ b/lib/Krawfish/Corpus/Span.pm
@@ -1,8 +1,9 @@
 package Krawfish::Corpus::Span;
-use Role::Tiny::With;
-with 'Krawfish::Corpus';
 use strict;
 use warnings;
+use Role::Tiny::With;
+
+with 'Krawfish::Corpus';
 
 # Search for intratextual features
 
diff --git a/lib/Krawfish/Koral.pm b/lib/Krawfish/Koral.pm
index 73e6680..6da68d4 100644
--- a/lib/Krawfish/Koral.pm
+++ b/lib/Krawfish/Koral.pm
@@ -1,8 +1,7 @@
 package Krawfish::Koral;
-use Role::Tiny::With;
 use strict;
 use warnings;
-with 'Krawfish::Koral::Report';
+use Role::Tiny::With;
 use Krawfish::Log;
 use Krawfish::Koral::Document;
 use Krawfish::Koral::Query::Builder;
@@ -10,6 +9,9 @@
 use Krawfish::Koral::Compile::Builder;
 use Krawfish::Koral::Compile;
 
+with 'Krawfish::Koral::Report';
+with 'Krawfish::Koral::Result::Inflatable';
+
 use constant DEBUG => 0;
 
 # Parse a koral query object and transform to an
@@ -58,12 +60,6 @@
 #   this should issue an update in the autosuggestion
 #   dictionary.
 
-# TODO:
-#   This is now double with Krawfish::Koral::Query!
-use constant {
-  CONTEXT => 'http://korap.ids-mannheim.de/ns/koral/0.6/context.jsonld'
-};
-
 sub new {
   my $class = shift;
   my $self = bless {
@@ -140,103 +136,12 @@
 };
 
 
-# sub response { ... };
-
-sub from_koral_query {
-  ...
-};
-
-
 # Clone the query object
 sub clone {
   ...
 };
 
 
-# This introduces the normalization phase
-# TODO:
-#   It should probably return a Koral::* object, that can be send!
-sub to_nodes {
-  my $self = shift;
-
-  # Optionally pass a node id for replication retrieval
-  my $replicant_id = shift;
-
-  # Build a complete query object
-  my $query;
-
-  # A virtual corpus and a query is given
-  if ($self->corpus && $self->query) {
-
-    # Filter query by corpus
-    $query = $self->query_builder->filter_by($self->query, $self->corpus);
-  }
-
-  # Only a query is given
-  elsif ($self->query) {
-
-    print_log('koral', 'Added live document filter') if DEBUG;
-
-    # Add corpus filter for live documents
-    $query = $self->query_builder->filter_by(
-      $self->query,
-      $self->corpus_builder->anywhere
-    );
-  }
-
-  # Only a corpus query is given
-  else {
-
-    # TODO:
-    #   This may have influence on the possible compile object!
-    $query = $self->corpus;
-  };
-
-  # If request is focused on replication, filter to replicates
-  if ($replicant_id) {
-    $query = $self->query_builder->filter_by(
-      $query,
-      $self->corpus_builder->replicant_node($replicant_id)
-    );
-  }
-
-  # Focus on primary data
-  else {
-    # $query = $self->query_builder->filter_by(
-    #   $query,
-    #   $self->corpus_builder->primary_node
-    # );
-  }
-
-  # Normalize the query
-  my $query_norm;
-  unless ($query_norm = $query->normalize) {
-    $self->copy_info_from($query);
-    return;
-  };
-
-  # Finalize the query
-  my $query_final;
-  unless ($query_final = $query_norm->finalize) {
-    $self->copy_info_from($query);
-    return;
-  };
-
-  # This is just for testing
-  return $query_final unless $self->compilation;
-
-  # Normalize the compile
-  my $compile;
-  unless ($compile = $self->compilation->normalize) {
-    $self->copy_info_from($self->compilation);
-    return;
-  };
-
-  # Serialize from compile
-  return $self->compilation->to_nodes($query_final);
-};
-
-
 # Create a single query tree
 sub to_query {
   my $self = shift;
@@ -328,20 +233,15 @@
 };
 
 
-# TODO:
-#   This is just temporarily, because results are still a mess!
-sub to_segments {
-  my ($self, $dict) = @_;
+sub inflate {
+  ...
 };
 
-
 # Serialization of KoralQuery
-sub to_koral_query {
+sub to_koral_fragment {
   my $self = shift;
 
-  my $koral = {
-    '@context' => CONTEXT
-  };
+  my $koral = {};
 
   # Set query object
   if ($self->query) {
@@ -380,38 +280,12 @@
 };
 
 
-
-
-
-
 # Get KoralQuery with results
 sub to_result {
   ...
 };
 
 
-# TODO:
-#   This is the new entry point!
-sub prepare_for_cluster {
-  # ->normalize->finalize->refer
-  ...
-};
-
-sub prepare_for_node {
-  # ->identify($dict)
-  # WARN! This may require a new normalization, but it should be kept in mind that this
-  # also may require double added warnings!
-  ...
-};
-
-sub prepare_for_segment {
-  # ->cache->optimize($segment)
-  ...
-};
-
-
-
-
 # Find identical subqueries and replace outer queries with
 # - references or
 # - cached queries
@@ -437,3 +311,118 @@
 
 
 __END__
+
+
+
+# TODO:
+#   This is the new entry point!
+sub prepare_for_cluster {
+  # ->normalize->finalize->refer
+  ...
+};
+
+sub prepare_for_node {
+  # ->identify($dict)
+  # WARN! This may require a new normalization, but it should be kept in mind that this
+  # also may require double added warnings!
+  ...
+};
+
+sub prepare_for_segment {
+  # ->cache->optimize($segment)
+  ...
+};
+
+
+
+# This introduces the normalization phase
+# TODO:
+#   It should probably return a Koral::* object, that can be send!
+sub to_nodes {
+  my $self = shift;
+
+  # Optionally pass a node id for replication retrieval
+  my $replicant_id = shift;
+
+  # Build a complete query object
+  my $query;
+
+  # A virtual corpus and a query is given
+  if ($self->corpus && $self->query) {
+
+    # Filter query by corpus
+    $query = $self->query_builder->filter_by($self->query, $self->corpus);
+  }
+
+  # Only a query is given
+  elsif ($self->query) {
+
+    print_log('koral', 'Added live document filter') if DEBUG;
+
+    # Add corpus filter for live documents
+    $query = $self->query_builder->filter_by(
+      $self->query,
+      $self->corpus_builder->anywhere
+    );
+  }
+
+  # Only a corpus query is given
+  else {
+
+    # TODO:
+    #   This may have influence on the possible compile object!
+    $query = $self->corpus;
+  };
+
+  # If request is focused on replication, filter to replicates
+  if ($replicant_id) {
+    $query = $self->query_builder->filter_by(
+      $query,
+      $self->corpus_builder->replicant_node($replicant_id)
+    );
+  }
+
+  # Focus on primary data
+  else {
+    # $query = $self->query_builder->filter_by(
+    #   $query,
+    #   $self->corpus_builder->primary_node
+    # );
+  }
+
+  # Normalize the query
+  my $query_norm;
+  unless ($query_norm = $query->normalize) {
+    $self->copy_info_from($query);
+    return;
+  };
+
+  # Finalize the query
+  my $query_final;
+  unless ($query_final = $query_norm->finalize) {
+    $self->copy_info_from($query);
+    return;
+  };
+
+  # This is just for testing
+  return $query_final unless $self->compilation;
+
+  # Normalize the compile
+  my $compile;
+  unless ($compile = $self->compilation->normalize) {
+    $self->copy_info_from($self->compilation);
+    return;
+  };
+
+  # Serialize from compile
+  return $self->compilation->to_nodes($query_final);
+};
+
+
+
+
+# TODO:
+#   This is just temporarily, because results are still a mess!
+sub to_segments {
+  my ($self, $dict) = @_;
+};
diff --git a/lib/Krawfish/Koral/Document/FieldBase.pm b/lib/Krawfish/Koral/Document/FieldBase.pm
index f53dc08..2e09855 100644
--- a/lib/Krawfish/Koral/Document/FieldBase.pm
+++ b/lib/Krawfish/Koral/Document/FieldBase.pm
@@ -52,6 +52,12 @@
 
 sub to_koral_fragment {
   my $self = shift;
+
+  unless ($self->key) {
+    warn 'Inflate!';
+    return;
+  };
+
   return {
     '@type' => 'koral:field',
     'type' => 'type:' . (
diff --git a/lib/Krawfish/Koral/Report.pm b/lib/Krawfish/Koral/Report.pm
index aaca5be..67f9e49 100644
--- a/lib/Krawfish/Koral/Report.pm
+++ b/lib/Krawfish/Koral/Report.pm
@@ -1,9 +1,14 @@
 package Krawfish::Koral::Report;
 use Role::Tiny;
+requires qw/error
+            warning
+            message
+            has_error
+            has_warning
+            has_message/;
+use Krawfish::Log;
 use strict;
 use warnings;
-use Krawfish::Log;
-requires qw/error warning message has_error has_warning has_message/;
 
 # Report on errors, warnings an anything else
 
diff --git a/lib/Krawfish/Koral/Result.pm b/lib/Krawfish/Koral/Result.pm
index ef69f4b..b9fa106 100644
--- a/lib/Krawfish/Koral/Result.pm
+++ b/lib/Krawfish/Koral/Result.pm
@@ -1,9 +1,21 @@
 package Krawfish::Koral::Result;
 use Role::Tiny::With;
 with 'Krawfish::Koral::Report';
+with 'Krawfish::Koral::Result::Inflatable';
 use strict;
 use warnings;
 
+# TODO:
+# It may be beneficial to have
+# - Aggregate
+# - Group
+# - Sort
+# - Enrich
+# on the same level as query and corpus
+# and remove the intermediate compile
+# directive!
+
+# Constructor
 sub new {
   my $class = shift;
   bless {
@@ -14,19 +26,6 @@
 };
 
 
-# Inflate results
-sub inflate {
-  my ($self, $dict) = @_;
-  foreach (@{$self->matches}) {
-    $_->inflate($dict);
-  };
-  foreach (@{$self->aggregation}) {
-    $_->inflate($dict);
-  };
-
-  $self;
-};
-
 # Add matches to the result
 sub add_match {
   my ($self, $match) = @_;
@@ -34,6 +33,7 @@
 };
 
 
+# Get list of matches
 sub matches {
   $_[0]->{matches};
 };
@@ -53,6 +53,7 @@
 };
 
 
+# Stringification
 sub to_string {
   my $self = shift;
   my $str = '';
@@ -78,20 +79,55 @@
   return $str;
 };
 
+# Inflate results
+sub inflate {
+  my ($self, $dict) = @_;
+  foreach (@{$self->matches}) {
+    $_->inflate($dict);
+  };
+  foreach (@{$self->aggregation}) {
+    $_->inflate($dict);
+  };
+
+  $self;
+};
+
 
 # Get koral result fragment
 sub to_koral_fragment {
   my $self = shift;
-  return {
+  my $result = {
     '@type' => 'koral:result',
-
-    # TODO:
-    #   Rename to 'compilation'
-    'collection' => $self->{collection}->to_koral_fragment,
-    'matches' => [
-      map { $_->to_koral_fragment } @{$self->{matches}}
-    ]
   };
+
+
+  # Add aggregation
+  if ($self->{aggregation}) {
+    # It is beneficial to be able to point to,
+    # e.g. the field frequencies without iterating
+    # through all aggregations.
+    # Therefor it is probably better to use the ->key
+    # to add aggregations instead of arrays.
+
+    my %aggr = ();
+    foreach (@{$self->{aggregation}}) {
+      $aggr{$_->key} = $_->to_koral_fragment;
+    };
+
+    $result->{aggregation} = \%aggr;
+  };
+
+  # Add matches
+  if ($self->{matches}) {
+    my @matches = ();
+    foreach (@{$self->{matches}}) {
+      push @matches, $_->to_koral_fragment;
+    };
+
+    $result->{matches} = \@matches;
+  };
+
+  return $result;
 };
 
 
diff --git a/lib/Krawfish/Koral/Result/Aggregate/Fields.pm b/lib/Krawfish/Koral/Result/Aggregate/Fields.pm
index d3868d1..4ddcff6 100644
--- a/lib/Krawfish/Koral/Result/Aggregate/Fields.pm
+++ b/lib/Krawfish/Koral/Result/Aggregate/Fields.pm
@@ -1,14 +1,16 @@
 package Krawfish::Koral::Result::Aggregate::Fields;
+use strict;
+use warnings;
+use Role::Tiny::With;
 use Krawfish::Log;
 use Krawfish::Util::Bits;
 use Krawfish::Util::Constants qw/:PREFIX/;
-use strict;
-use warnings;
+
+with 'Krawfish::Koral::Result::Inflatable';
 
 # This remembers facets for multiple classes,
 # both using ids and terms
 
-
 # TODO:
 #   The first field level should be initiated
 #   beforehand, so it is not necessary to check
@@ -246,7 +248,7 @@
   my @classes = @{$self->_to_classes};
   my $first = 0;
   foreach (my $i = 0; $i < @classes; $i++) {
-    $str .= $i == 0 ? 'total' : 'inCorpus' . $i;
+    $str .= $i == 0 ? 'total' : 'inCorpus-' . $i;
     $str .= ':[';
 
     my $fields = $classes[$i];
@@ -276,6 +278,48 @@
 };
 
 
+# Serialize to KQ
+sub to_koral_fragment {
+  my $self = shift;
+  my $aggr = {
+    '@type' => 'koral:aggregation',
+    'aggregation' => 'aggregation:fields'
+  };
+
+  # No terms yet
+  unless ($self->{fields_terms}) {
+    warn 'ID based stringification currently not supported';
+    return;
+  };
+
+
+  my @classes = @{$self->_to_classes};
+  my $first = 0;
+  foreach (my $i = 0; $i < @classes; $i++) {
+    my $per_field = $aggr->{$i == 0 ? 'total' : 'inCorpus-' . $i} = {};
+    my $fields = $classes[$i];
+
+    # Store per field
+    foreach my $field (sort keys %$fields) {
+
+      # Get values
+      my $values = $fields->{$field};
+
+      # Iterate over values
+      foreach (keys %$values) {
+        my $freq = $values->{$_};
+        my $per_value = $per_field->{$field} //= {};
+        $per_value->{$_} = {
+          docs => $freq->[0],
+          matches => $freq->[1]
+        };
+      };
+    };
+  };
+
+  return $aggr;
+};
+
 1;
 
 
diff --git a/lib/Krawfish/Koral/Result/Aggregate/Frequencies.pm b/lib/Krawfish/Koral/Result/Aggregate/Frequencies.pm
index 47c8cf2..fd7c8c6 100644
--- a/lib/Krawfish/Koral/Result/Aggregate/Frequencies.pm
+++ b/lib/Krawfish/Koral/Result/Aggregate/Frequencies.pm
@@ -1,8 +1,11 @@
 package Krawfish::Koral::Result::Aggregate::Frequencies;
-use Krawfish::Koral::Result::Aggregate::Length;
-use Krawfish::Util::Bits;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Koral::Result::Aggregate::Length;
+use Krawfish::Util::Bits;
+
+with 'Krawfish::Koral::Result::Inflatable';
 
 # This calculates frequencies for all classes
 
@@ -21,6 +24,10 @@
 };
 
 
+sub key {
+  'frequencies';
+};
+
 # Increment value per document
 sub incr_doc {
   my ($self, $flags) = @_;
@@ -83,7 +90,7 @@
 
   my $first = 0;
   foreach (my $i = 0; $i < @classes; $i++) {
-    $str .= $i == 0 ? 'total' : 'inCorpus' . $i;
+    $str .= $i == 0 ? 'total' : 'inCorpus-' . $i;
     $str .= ':[' . $classes[$i]->[0] . ',' .  $classes[$i]->[1] . ']';
     $str .= ';';
   };
@@ -92,8 +99,24 @@
 };
 
 
-sub key {
-  'frequencies';
+# Serialize to KQ
+sub to_koral_fragment {
+  my $self = shift;
+  my $aggr = {
+    '@type' => 'koral:aggregation',
+    'aggregation' => 'aggregation:frequencies'
+  };
+
+  my @classes = @{$self->_to_classes};
+  my $first = 0;
+  foreach (my $i = 0; $i < @classes; $i++) {
+    $aggr->{$i == 0 ? 'total' : 'inCorpus-' . $i} = {
+      docs => $classes[$i]->[0],
+      matches => $classes[$i]->[1]
+    };
+  };
+
+  return $aggr;
 };
 
 1;
diff --git a/lib/Krawfish/Koral/Result/Aggregate/Length.pm b/lib/Krawfish/Koral/Result/Aggregate/Length.pm
index 4af332c..46c8c34 100644
--- a/lib/Krawfish/Koral/Result/Aggregate/Length.pm
+++ b/lib/Krawfish/Koral/Result/Aggregate/Length.pm
@@ -1,7 +1,10 @@
 package Krawfish::Koral::Result::Aggregate::Length;
-use Krawfish::Util::Bits;
 use strict;
 use warnings;
+use Krawfish::Util::Bits;
+use Role::Tiny::With;
+
+with 'Krawfish::Koral::Result::Inflatable';
 
 # This calculates match length for all
 # corpus classes.
@@ -102,7 +105,7 @@
   foreach (my $i = 0; $i < @classes; $i++) {
 
     my $length = $classes[$i];
-    $str .= $i == 0 ? 'total' : 'inCorpus' . $i;
+    $str .= $i == 0 ? 'total' : 'inCorpus-' . $i;
     $str .= ':[';
     $str .= 'avg:' .  $length->{avg} . ',';
     $str .= 'freq:' . $length->{freq} . ',';
@@ -116,6 +119,33 @@
 };
 
 
+# Serialize to KQ
+sub to_koral_fragment {
+  my $self = shift;
+
+  my $aggr = {
+    '@type' => 'koral:aggregation',
+    'aggregation' => 'aggregation:length'
+  };
+
+  my @classes = @{$self->_to_classes};
+  my $first = 0;
+  foreach (my $i = 0; $i < @classes; $i++) {
+    my $length = $classes[$i];
+
+    $aggr->{$i == 0 ? 'total' : 'inCorpus-' . $i} = {
+      'avg'  =>  $length->{avg},
+      'freq' => $length->{freq},
+      'min'  => $length->{min},
+      'max'  => $length->{max},
+      'sum'  => $length->{sum}
+    };
+  };
+
+  return $aggr;
+};
+
+
 sub key {
   'length';
 };
diff --git a/lib/Krawfish/Koral/Result/Aggregate/Values.pm b/lib/Krawfish/Koral/Result/Aggregate/Values.pm
index 727b388..ab4dd2d 100644
--- a/lib/Krawfish/Koral/Result/Aggregate/Values.pm
+++ b/lib/Krawfish/Koral/Result/Aggregate/Values.pm
@@ -1,7 +1,10 @@
 package Krawfish::Koral::Result::Aggregate::Values;
-use Krawfish::Util::Bits;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Util::Bits;
+
+with 'Krawfish::Koral::Result::Inflatable';
 
 # Support of classes is relevant, e.g. to compare the size
 # of subcorpora.
@@ -149,7 +152,7 @@
   my @classes = @{$self->_to_classes};
   my $first = 0;
   foreach (my $i = 0; $i < @classes; $i++) {
-    $str .= $i == 0 ? 'total' : 'inCorpus' . $i;
+    $str .= $i == 0 ? 'total' : 'inCorpus-' . $i;
     $str .= ':[';
 
     my $fields = $classes[$i];
@@ -177,6 +180,36 @@
 };
 
 
+sub to_koral_fragment {
+  my $self = shift;
+  my $aggr = {
+    '@type' => 'koral:aggregation',
+    'aggregation' => 'aggregation:values'
+  };
+
+  my @classes = @{$self->_to_classes};
+  my $first = 0;
+  foreach (my $i = 0; $i < @classes; $i++) {
+    my $val = $aggr->{$i == 0 ? 'total' : 'inCorpus-' . $i} = {};
+    my $fields = $classes[$i];
+
+    foreach my $field (sort keys %$fields) {
+      my $values = $fields->{$field};
+
+      # Set values per field
+      $val->{$field} = {
+        'sum'  => $values->{sum},
+        'freq' => $values->{freq},
+        'min'  => $values->{min},
+        'max'  => $values->{max},
+        'avg'  => $values->{avg}
+      };
+    };
+  };
+
+  return $aggr;
+};
+
 
 # Finish the aggregation
 sub on_finish {
diff --git a/lib/Krawfish/Koral/Result/Enrich/CorpusClasses.pm b/lib/Krawfish/Koral/Result/Enrich/CorpusClasses.pm
index 10a024a..8f18847 100644
--- a/lib/Krawfish/Koral/Result/Enrich/CorpusClasses.pm
+++ b/lib/Krawfish/Koral/Result/Enrich/CorpusClasses.pm
@@ -1,6 +1,10 @@
 package Krawfish::Koral::Result::Enrich::CorpusClasses;
 use strict;
 use warnings;
+use Role::Tiny::With;
+
+with 'Krawfish::Koral::Report';
+with 'Krawfish::Koral::Result::Inflatable';
 
 # The classes are only numbers (1..15)
 
@@ -18,13 +22,6 @@
   $_[0];
 };
 
-
-# Key for enrichment
-sub key {
-  'inCorpus';
-};
-
-
 # Stringification
 sub to_string {
   my $self = shift;
@@ -32,6 +29,11 @@
 };
 
 
+# Key for enrichment
+sub key {
+  'inCorpus';
+};
+
 # Serialize to KoralQuery
 sub to_koral_fragment {
   $_[0]->{classes};
diff --git a/lib/Krawfish/Koral/Result/Enrich/Fields.pm b/lib/Krawfish/Koral/Result/Enrich/Fields.pm
index f6d36a7..40e2e4b 100644
--- a/lib/Krawfish/Koral/Result/Enrich/Fields.pm
+++ b/lib/Krawfish/Koral/Result/Enrich/Fields.pm
@@ -1,6 +1,9 @@
 package Krawfish::Koral::Result::Enrich::Fields;
 use strict;
 use warnings;
+use Role::Tiny::With;
+
+with 'Krawfish::Koral::Result::Inflatable';
 
 # The fields are represented as Krawfish::Koral::Document::Field* objects!
 
diff --git a/lib/Krawfish/Koral/Result/Group.pm b/lib/Krawfish/Koral/Result/Group.pm
index 9fb45a8..b199c31 100644
--- a/lib/Krawfish/Koral/Result/Group.pm
+++ b/lib/Krawfish/Koral/Result/Group.pm
@@ -1,7 +1,11 @@
 package Krawfish::Koral::Result::Group;
+use Role::Tiny::With;
 use strict;
 use warnings;
 
+with 'Krawfish::Koral::Report';
+with 'Krawfish::Koral::Result::Inflatable';
+
 # This will be returned by a Group search
 # It needs a to_hash method,
 # does not require start, end etc ...
diff --git a/lib/Krawfish/Koral/Result/Inflatable.pm b/lib/Krawfish/Koral/Result/Inflatable.pm
new file mode 100644
index 0000000..8f96720
--- /dev/null
+++ b/lib/Krawfish/Koral/Result/Inflatable.pm
@@ -0,0 +1,22 @@
+package Krawfish::Koral::Result::Inflatable;
+use Role::Tiny;
+requires qw/inflate
+            to_string
+            to_koral_fragment/;
+
+# TODO:
+#   This is now double with Krawfish::Koral::Query!
+use constant {
+  CONTEXT => 'http://korap.ids-mannheim.de/ns/koral/0.6/context.jsonld'
+};
+
+
+# Wrap the fragment in context
+sub to_koral_query {
+  my $self = shift;
+  my $koral = $self->to_koral_fragment;
+  $koral->{'@context'} = CONTEXT;
+  return $koral;
+};
+
+1;
diff --git a/lib/Krawfish/Koral/Result/Match.pm b/lib/Krawfish/Koral/Result/Match.pm
index a05b477..fc398b2 100644
--- a/lib/Krawfish/Koral/Result/Match.pm
+++ b/lib/Krawfish/Koral/Result/Match.pm
@@ -1,9 +1,13 @@
 package Krawfish::Koral::Result::Match;
-use parent 'Krawfish::Posting::Span';
+use Role::Tiny::With;
 use Krawfish::Util::String qw/squote/;
 use warnings;
 use strict;
 
+with 'Krawfish::Koral::Report';
+with 'Krawfish::Posting::Span';
+with 'Krawfish::Koral::Result::Inflatable';
+
 # TODO:
 #   Move Posting::Match, Posting::Aggregate, Posting::Group,
 #   Posting etc. to Koral::Result
diff --git a/lib/Krawfish/Posting.pm b/lib/Krawfish/Posting.pm
index 5679146..bd67932 100644
--- a/lib/Krawfish/Posting.pm
+++ b/lib/Krawfish/Posting.pm
@@ -1,18 +1,19 @@
 package Krawfish::Posting;
+use strict;
+use warnings;
 use Role::Tiny;
+use overload '""' => sub { $_[0]->to_string }, fallback => 1;
+use Krawfish::Util::Bits;
+use Krawfish::Posting::Payload;
+use Krawfish::Log;
+use bytes;
+
 requires qw/doc_id
            flags
            corpus_classes
            same_as
            to_string
            clone/;
-use overload '""' => sub { $_[0]->to_string }, fallback => 1;
-use Krawfish::Util::Bits;
-use Krawfish::Posting::Payload;
-use Krawfish::Log;
-use bytes;
-use strict;
-use warnings;
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query.pm b/lib/Krawfish/Query.pm
index 36d0539..7b4ea91 100644
--- a/lib/Krawfish/Query.pm
+++ b/lib/Krawfish/Query.pm
@@ -1,14 +1,15 @@
 package Krawfish::Query;
+use strict;
+use warnings;
 use Role::Tiny;
+use Krawfish::Log;
+use Krawfish::Posting::Span;
+use Scalar::Util qw/blessed refaddr/;
+
 with 'Krawfish::Corpus';
 requires qw/skip_pos
             filter_by
             requires_filter/;
-use Krawfish::Log;
-use Krawfish::Posting::Span;
-use Scalar::Util qw/blessed refaddr/;
-use strict;
-use warnings;
 
 
 # Krawfish::Query is the base class for all span queries.
diff --git a/lib/Krawfish/Query/Base/Sorted.pm b/lib/Krawfish/Query/Base/Sorted.pm
index 6d06480..d74d6c3 100644
--- a/lib/Krawfish/Query/Base/Sorted.pm
+++ b/lib/Krawfish/Query/Base/Sorted.pm
@@ -1,10 +1,11 @@
 package Krawfish::Query::Base::Sorted;
 use Role::Tiny::With;
-with 'Krawfish::Query';
 use Krawfish::Log;
 use strict;
 use warnings;
 
+with 'Krawfish::Query';
+
 use constant DEBUG => 0;
 
 # Base query for queries that may be unsorted.
diff --git a/lib/Krawfish/Query/Cache.pm b/lib/Krawfish/Query/Cache.pm
index d2b5b78..e6461d6 100644
--- a/lib/Krawfish/Query/Cache.pm
+++ b/lib/Krawfish/Query/Cache.pm
@@ -1,10 +1,11 @@
 package Krawfish::Query::Cache;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Index::Stream;
-use Krawfish::Cache;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Index::Stream;
+use Krawfish::Cache;
+
+with 'Krawfish::Query';
 
 # Cache implementation for queries
 
diff --git a/lib/Krawfish/Query/Class.pm b/lib/Krawfish/Query/Class.pm
index 89e8475..337c17a 100644
--- a/lib/Krawfish/Query/Class.pm
+++ b/lib/Krawfish/Query/Class.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Class;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/Constraints.pm b/lib/Krawfish/Query/Constraints.pm
index 3f4902d..1832258 100644
--- a/lib/Krawfish/Query/Constraints.pm
+++ b/lib/Krawfish/Query/Constraints.pm
@@ -1,12 +1,13 @@
 package Krawfish::Query::Constraints;
+use strict;
+use warnings;
 use Role::Tiny::With;
-with 'Krawfish::Query::Base::Dual';
-with 'Krawfish::Query';
 use Krawfish::Util::Buffer;
 use List::Util qw/min/;
 use Krawfish::Log;
-use strict;
-use warnings;
+
+with 'Krawfish::Query::Base::Dual';
+with 'Krawfish::Query';
 
 # TODO:
 #   Improve by skipping to the same document
diff --git a/lib/Krawfish/Query/Exclusion.pm b/lib/Krawfish/Query/Exclusion.pm
index 9a614c0..6a24a73 100644
--- a/lib/Krawfish/Query/Exclusion.pm
+++ b/lib/Krawfish/Query/Exclusion.pm
@@ -1,15 +1,17 @@
 package Krawfish::Query::Exclusion;
-use Role::Tiny::With;
-with 'Krawfish::Query::Base::Dual';
-with 'Krawfish::Query';
-use Krawfish::Query::Base::Dual;
-use Krawfish::Query::Constraint::Position; # Export constants and @next_a and @next_b
-use Krawfish::Util::Bits; # exports bitstring
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Query::Base::Dual;
+# Export constants and @next_a and @next_b
+use Krawfish::Query::Constraint::Position;
+use Krawfish::Util::Bits; # exports bitstring
+use Krawfish::Log;
 use bytes;
 
+with 'Krawfish::Query::Base::Dual';
+with 'Krawfish::Query';
+
 # This query validates positional constraints
 # that are exclusive returns a valid forwarding mechanism
 
diff --git a/lib/Krawfish/Query/Extension.pm b/lib/Krawfish/Query/Extension.pm
index f0ef5af..f29dff4 100644
--- a/lib/Krawfish/Query/Extension.pm
+++ b/lib/Krawfish/Query/Extension.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Extension;
-use Role::Tiny::With;
-with 'Krawfish::Query::Base::Dual';
-with 'Krawfish::Query';
 use strict;
 use warnings;
+use Role::Tiny::With;
+
+with 'Krawfish::Query::Base::Dual';
+with 'Krawfish::Query';
 
 # This query adds subtokens to the left or the right
 # of a matching span
diff --git a/lib/Krawfish/Query/Filter.pm b/lib/Krawfish/Query/Filter.pm
index 344e60d..c34fd7b 100644
--- a/lib/Krawfish/Query/Filter.pm
+++ b/lib/Krawfish/Query/Filter.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Filter;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/InCorpus.pm b/lib/Krawfish/Query/InCorpus.pm
index 0ac6327..a5787e2 100644
--- a/lib/Krawfish/Query/InCorpus.pm
+++ b/lib/Krawfish/Query/InCorpus.pm
@@ -1,10 +1,11 @@
 package Krawfish::Query::InCorpus;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Util::Bits;
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Util::Bits;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 # Filter matches occuring in the wrong
 # subcorpus. This is helpful in comparable corpora,
diff --git a/lib/Krawfish/Query/Length.pm b/lib/Krawfish/Query/Length.pm
index 44680c8..a3f2548 100644
--- a/lib/Krawfish/Query/Length.pm
+++ b/lib/Krawfish/Query/Length.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Length;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/Match.pm b/lib/Krawfish/Query/Match.pm
index cbbfa97..6e3926e 100644
--- a/lib/Krawfish/Query/Match.pm
+++ b/lib/Krawfish/Query/Match.pm
@@ -1,10 +1,10 @@
 package Krawfish::Query::Match;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
 
+with 'Krawfish::Query';
 
 # Get posting by doc id plus position and length.
 
diff --git a/lib/Krawfish/Query/Nowhere.pm b/lib/Krawfish/Query/Nowhere.pm
index 4c3bf82..5ab9c5f 100644
--- a/lib/Krawfish/Query/Nowhere.pm
+++ b/lib/Krawfish/Query/Nowhere.pm
@@ -1,8 +1,9 @@
 package Krawfish::Query::Nowhere;
-use Role::Tiny::With;
-with 'Krawfish::Query';
 use strict;
 use warnings;
+use Role::Tiny::With;
+
+with 'Krawfish::Query';
 
 # This is a query that returns nowhere
 sub new {
diff --git a/lib/Krawfish/Query/Or.pm b/lib/Krawfish/Query/Or.pm
index c0387f8..3052852 100644
--- a/lib/Krawfish/Query/Or.pm
+++ b/lib/Krawfish/Query/Or.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Or;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/Reference.pm b/lib/Krawfish/Query/Reference.pm
index 2ec1e2a..1233dd4 100644
--- a/lib/Krawfish/Query/Reference.pm
+++ b/lib/Krawfish/Query/Reference.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Reference;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 # TODO:
 #   This is not an actual query,
diff --git a/lib/Krawfish/Query/Repetition.pm b/lib/Krawfish/Query/Repetition.pm
index a5f298e..9053ff0 100644
--- a/lib/Krawfish/Query/Repetition.pm
+++ b/lib/Krawfish/Query/Repetition.pm
@@ -1,11 +1,12 @@
 package Krawfish::Query::Repetition;
+use strict;
+use warnings;
 use Role::Tiny::With;
-with 'Krawfish::Query';
 use Krawfish::Util::Buffer;
 use Krawfish::Log;
 use Krawfish::Posting;
-use strict;
-use warnings;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/TermID.pm b/lib/Krawfish/Query/TermID.pm
index f879da1..776716d 100644
--- a/lib/Krawfish/Query/TermID.pm
+++ b/lib/Krawfish/Query/TermID.pm
@@ -1,11 +1,12 @@
 package Krawfish::Query::TermID;
+use strict;
+use warnings;
 use Role::Tiny::With;
-with 'Krawfish::Query';
 use Krawfish::Posting::Span;
 use Krawfish::Query::Filter;
 use Krawfish::Log;
-use strict;
-use warnings;
+
+with 'Krawfish::Query';
 
 use constant DEBUG => 0;
 
diff --git a/lib/Krawfish/Query/Unique.pm b/lib/Krawfish/Query/Unique.pm
index 8dedb9a..5547792 100644
--- a/lib/Krawfish/Query/Unique.pm
+++ b/lib/Krawfish/Query/Unique.pm
@@ -1,9 +1,10 @@
 package Krawfish::Query::Unique;
-use Role::Tiny::With;
-with 'Krawfish::Query';
-use Krawfish::Log;
 use strict;
 use warnings;
+use Role::Tiny::With;
+use Krawfish::Log;
+
+with 'Krawfish::Query';
 
 # Filter duplicate postings
 
diff --git a/t/compile/segment/aggregate_fields.t b/t/compile/segment/aggregate_fields.t
index 2a8023a..fe33892 100644
--- a/t/compile/segment/aggregate_fields.t
+++ b/t/compile/segment/aggregate_fields.t
@@ -114,8 +114,6 @@
  );
 
 
-
-
 # Create compile query to aggregate on 'author'
 $koral->compilation(
   $mb->aggregate(
@@ -142,12 +140,20 @@
 is($coll->to_string,
    '[aggr=[fields='.
      'total:[author=Fritz:[1,2],Michael:[1,1],Peter:[3,4]];'.
-     'inCorpus1:[author=Fritz:[1,2],Michael:[1,1],Peter:[1,2]];'.
-     'inCorpus2:[author=Peter:[2,2]]]]'.
+     'inCorpus-1:[author=Fritz:[1,2],Michael:[1,1],Peter:[1,2]];'.
+     'inCorpus-2:[author=Peter:[2,2]]]]'.
      '[matches=[0:0-1!2][1:0-1!2][2:0-1!1][2:2-3!1][4:0-1!1]]',
    'Stringification'
  );
 
+ok($coll = $coll->to_koral_query->{aggregation}->{fields}, 'KQ Serialization');
+
+is($coll->{total}->{author}->{Peter}->{docs}, 3, 'Values');
+is($coll->{total}->{author}->{Peter}->{matches}, 4, 'Values');
+is($coll->{total}->{author}->{Fritz}->{matches}, 2, 'Values');
+is($coll->{total}->{author}->{Michael}->{matches}, 1, 'Values');
+is($coll->{'inCorpus-1'}->{author}->{Fritz}->{matches}, 2, 'Values');
+
 
 done_testing;
 __END__
diff --git a/t/compile/segment/aggregate_freq.t b/t/compile/segment/aggregate_freq.t
index a8e0f3b..1964d43 100644
--- a/t/compile/segment/aggregate_freq.t
+++ b/t/compile/segment/aggregate_freq.t
@@ -58,10 +58,19 @@
 
 # is($query->to_string, 'aggr([freq]:filter(#6,[1]))', 'Stringification');
 
-is($query->compile->to_string,
+ok(my $comp = $query->compile->inflate($index->dict), 'Compilation');
+is($comp->to_string,
    '[aggr=[freq=total:[2,2]]][matches=[0:1-2][2:1-2]]',
    'Aggregation');
 
+# Test serialization
+is($comp->to_koral_query->{'aggregation'}->{frequencies}->{aggregation},
+   'aggregation:frequencies',
+   'Check KQ');
+is($comp->to_koral_query->{'aggregation'}->{frequencies}->{total}->{matches},
+   2,
+   'Check KQ');
+
 
 # Test with imbalance regarding docs and matches
 $koral = Krawfish::Koral->new;
@@ -119,7 +128,7 @@
 
 # Search till the end
 is($query->compile->to_string,
-   '[aggr=[freq=total:[3,7];inCorpus1:[2,4];inCorpus2:[1,3]]]'.
+   '[aggr=[freq=total:[3,7];inCorpus-1:[2,4];inCorpus-2:[1,3]]]'.
      '[matches=[0:0-1!1][0:0-2!1][1:0-1!2][1:0-2!2][1:0-3!2][2:0-1!1][2:0-2!1]]',
    'Finish');
 
diff --git a/t/compile/segment/aggregate_length.t b/t/compile/segment/aggregate_length.t
index 3cf0101..2f3c03f 100644
--- a/t/compile/segment/aggregate_length.t
+++ b/t/compile/segment/aggregate_length.t
@@ -63,6 +63,13 @@
      '[matches=[0:0-2][1:0-1][2:0-1][2:1-4]]',
    'Stringification');
 
+ok($coll = $coll->to_koral_query->{aggregation}->{length}, 'Serialize KQ');
+is($coll->{aggregation},
+   'aggregation:length',
+   'KQ serialization');
+
+is($coll->{total}->{sum}, 7,
+   'KQ serialization');
 
 $koral = Krawfish::Koral->new;
 $koral->query($qb->span('s'));
@@ -89,8 +96,8 @@
 is(
   $koral_query->to_string,
   '[aggr=[length=total:[avg:1.75,freq:4,min:1,max:3,sum:7];'.
-    'inCorpus1:[avg:2,freq:1,min:2,max:2,sum:2];'.
-    'inCorpus2:[avg:1.66666666666667,freq:3,min:1,max:3,sum:5]]]'.
+    'inCorpus-1:[avg:2,freq:1,min:2,max:2,sum:2];'.
+    'inCorpus-2:[avg:1.66666666666667,freq:3,min:1,max:3,sum:5]]]'.
     '[matches=[0:0-2!1][1:0-1!2][2:0-1!2][2:1-4!2]]',
   'Stringification');
 
diff --git a/t/compile/segment/aggregate_values.t b/t/compile/segment/aggregate_values.t
index 9e2cf7d..0b47d9e 100644
--- a/t/compile/segment/aggregate_values.t
+++ b/t/compile/segment/aggregate_values.t
@@ -135,11 +135,18 @@
 is($coll->to_string,
    '[aggr=[values='.
      'total:[size:[sum:9,freq:3,min:2,max:5,avg:3]];'.
-     'inCorpus1:[size:[sum:2,freq:1,min:2,max:2,avg:2]];'.
-     'inCorpus2:[size:[sum:7,freq:2,min:2,max:5,avg:3.5]]]]'.
+     'inCorpus-1:[size:[sum:2,freq:1,min:2,max:2,avg:2]];'.
+     'inCorpus-2:[size:[sum:7,freq:2,min:2,max:5,avg:3.5]]]]'.
      '[matches=[0:1-2!1][2:1-2!2][3:1-2!2][3:3-4!2]]',
    'Stringification');
 
 
+my $json = $coll->to_koral_query->{aggregation}->{values};
+is($json->{total}->{size}->{avg}, 3, 'KQ serialization');
+is($json->{'inCorpus-1'}->{size}->{avg}, 2, 'KQ serialization');
+is($json->{'inCorpus-2'}->{size}->{sum}, 7, 'KQ serialization');
+is($json->{aggregation}, 'aggregation:values', 'KQ serialization');
+
+
 done_testing;
 __END__
diff --git a/t/compile/segment/enrich_fields.t b/t/compile/segment/enrich_fields.t
index 94354ca..273be53 100644
--- a/t/compile/segment/enrich_fields.t
+++ b/t/compile/segment/enrich_fields.t
@@ -139,6 +139,29 @@
 
 
 
+
+$koral = Krawfish::Koral->new;
+$koral->query($qb->token('aa'));
+$koral->compilation(
+  $mb->enrich(
+    $mb->e_fields('license','corpus')
+  )
+);
+
+my $result = $koral->to_query
+  ->identify($index->dict)
+  ->optimize($index->segment)
+  ->compile
+  ->inflate($index->dict);
+
+ok($kq = $result->to_koral_query, 'Serialize KQ');
+
+my $first_fields = $kq->{matches}->[0]->{fields};
+is($first_fields->[0]->{key}, 'corpus');
+is($first_fields->[0]->{value}, 'corpus-2');
+is($first_fields->[1]->{key}, 'license');
+is($first_fields->[1]->{value}, 'free');
+
 done_testing;
 __END__
 
diff --git a/t/koral/filter.t b/t/koral/filter.t
index 7ae7bd8..7114fb9 100644
--- a/t/koral/filter.t
+++ b/t/koral/filter.t
@@ -33,7 +33,7 @@
 
 is($koral->to_string, 'corpus=[author=Peter],query=[bb]', 'Stringification');
 
-my $query = $koral->to_nodes->identify($index->dict);
+my $query = $koral->to_query->identify($index->dict);
 is($query->to_string, "[0]", 'Planned stringification');
 ok($query = $query->optimize($index->segment), 'Optimize');
 is($query->to_string, "[0]", 'Planned stringification');
@@ -42,7 +42,7 @@
 
 is($koral->to_string, 'corpus=[author=Arthur],query=[bb]', 'Stringification');
 
-$query = $koral->to_nodes->identify($index->dict)->optimize($index->segment);
+$query = $koral->to_query->identify($index->dict)->optimize($index->segment);
 
 
 # Can't match anywhere:
diff --git a/t/koral/query.t b/t/koral/query.t
index 41065b3..ec1480b 100644
--- a/t/koral/query.t
+++ b/t/koral/query.t
@@ -93,7 +93,7 @@
 
 TODO: {
   local $TODO = 'Test Serialization output';
-  ok($koral = $koral->to_nodes, 'Finalize query');
+  ok($koral = $koral->to_query, 'Finalize query');
 };