title: Elastic Search- Distinct elements from multiple fields
body: <p>I created a mapping to index my <code>mongoDb</code> collection using elastic search. Here is the <code>mapping</code> properties:</p>
  
  <pre><code>"properties" : {
            "address_components" : {
              "properties" : {
                "_id" : {
                  "type" : "string"
                },
                "subLocality1" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                },
                "subLocality2" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                },
                "subLocality3" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }, 
               "city" : {
                  "type" : "string",
                  "index" : "not_analyzed"
                }
              }
  </code></pre>
  
  <p>Now, I want to retrieve overall unique items from these fields: <code>subLocality1</code>, <code>subLocality2</code>, <code>subLocality3</code>, <code>city</code>. 
  Also, each of the <code>distinct</code> value should contain <code>q</code> as a sub-string. 
  Distinct item should also contain corresponding <code>city</code> value.</p>
  
  <p>Example:</p>
  
  <pre><code>"address_components" : {
      "subLocality1" : "s1"
      "subLocality2" : "s1",
      "subLocality3" : "s2",
      "city":"a"
    }
  
  "address_components" : {
      "subLocality1" : "s3"
      "subLocality2" : "s1",
      "subLocality3" : "s2",
      "city":"a"
    }
  
  "address_components" : {
      "subLocality1" : "s2"
      "subLocality2" : "s1",
      "subLocality3" : "s4",
      "city":"a"
    }
  </code></pre>
  
  <p>For above indexes,
  the expected result is:</p>
  
  <pre><code>"address_components" : {
      "subLocality1" : "s1"
      "subLocality2" : "s1",
      "subLocality3" : "s2",
      "city":"ct1"
    }
  
  "address_components" : {
      "subLocality1" : "s3"
      "subLocality2" : "s1",
      "subLocality3" : "s2",
      "city":"ct1"
    }
  
  "address_components" : {
      "subLocality1" : "s2"
      "subLocality2" : "s1",
      "subLocality3" : "s4",
      "city":"ct1"
    }
  {s1, a}, {s2,a}, {s3,a}, {s4,a},{a,a}
  </code></pre>
  
  <p>I tried doing it using elastic search <code>terms</code> aggregation. </p>
  
  <pre><code>GET /rescu/rescu/_search?pretty=true&amp;search_type=count
  
  {
      "aggs" : {
          "distinct_locations" : {
              "terms" : {
                  "script" : "doc['address_components.subLocality1'].value"
              }
          }
      }
  }
  </code></pre>
  
  <p>But <code>terms</code> aggregations only applies for single field according to following <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_multi_field_terms_aggregation" rel="noreferrer">link</a>.</p>