title: Aggregate and Sort by a text field and concatenate other text fields in Elasticsearch
body: <p>In Elasticsearch, how does one <strong>aggregate and sort</strong> by a text field and concatenate field values of other text fields, joined by e.g. <code>;</code> ?</p>
  
  <p>In concatenating I mean to concatenate values of the same field from all the aggregated documents, <strong>not</strong> values of different fields from the same document.</p>
  
  <p><strong>Details</strong></p>
  
  <p>I have small documents with fields gene, tag, annotation described as</p>
  
  <pre><code>{
    "mappings": {
      "annotations": {
        "properties": {
          "species": {
            "type": "text"
          },
          "gene": {
            "type": "text",
            "fields": {
              "keyword": { 
                "type": "keyword"
              }  
            }
          },
          "tag": {
            "type": "text"
          },
          "annotation": {
            "type": "text"
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>There are many entries per gene. That is, I have:</p>
  
  <pre><code>Gene  Tag   Annotation
  ----- ----- ---------------
  A1BG  tag1  first gene
  A2M   tag1  a-macroglobulin
  A2M   tag2  second gene
  BRCA1 tag1  breast cancer 1
  BRCA1 tag3  important gene
  </code></pre>
  
  <p>I want to query these data, aggregate and sort by gene, and get something like this:</p>
  
  <pre><code>Gene   Tags        Annotations
  ------ ----------- -------------------------------
  A1BG   tag1        first gene
  A2M    tag1; tag2  a-macroglobulin; second gene
  BRCA1  tag1; tag3  breast cancer 1; important gene
  </code></pre>
  
  <p>I can not find anything meaningful after googling for more than a day. Elasticsearch examples mostly show statistics e.g. counts, a few examples about concatenating fields from the same document but I could not find a way to concatenate the values of the same field. I tried to use <code>map</code> as well as something like this:</p>
  
  <pre><code>{
      "aggs" : {
          "genes_agg" : {
              "terms" : {
                  "script" : {
                      "source": "doc['tag'].join('; ')",
                      "lang": "painless"
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>but nothing works.</p>