Is it possible to get contents of copy_to field in Elasticsearch?

ov7a picture ov7a · Apr 14, 2016 · Viewed 7.6k times · Source

I'm using Elasticsearch v2.3.0. Suppose I have an index with mapping:

{
"mappings": {
  "post": {
    "dynamic": false,
    "_source": {
      "enabled": true
    },
    "properties": {
      "text": {
        "norms": {
          "enabled": false
        },
        "fielddata": {
          "format": "disabled"
        },
        "analyzer": "text_analyzer",
        "type": "string"
      },
      "subfield": {
        "properties": {
          "subsubfield": {
            "properties": {
              "subtext": {
                "index": "no",
                "analyzer": "text_analyzer",
                "type": "string",
                "copy_to": "text"
              }
            }  
          }
        }
      }
    },
    "_all": {
      "enabled": false
    }
  }
}

So, text from subfield.subsubfield.subtext is copied to text field due to copy_to. If you query a post, then only data from text is shown in text field, because _source is not modified. If you want to obtain all text, you should aggregate all fields on client. This can be inconvenient if there are many subfields.

Is there a magic query, which allows to get text field with all text copied to it?

Answer

keety picture keety · Apr 14, 2016

In the mapping for text field set "store":"yes" The you should be able to fetch it using fields

Example:

put test/test/_mapping
{
  "properties" : {
   "name" : { "type" : "string","copy_to": "text"},
   "text" : {"type" : "string" ,"store" :"yes"},
    "subfield": {
        "properties": {
          "subsubfield": {
            "properties": {
              "subtext": {
                "index": "no",
                "type": "string",
                "copy_to": "text"
              }
            }  
          }
        }
      }
  }   

}

put test/test/1 
{
    "name" : "hello",
    "subfield" : {
        "subsubfield" : [
            {"subtext" : "soundgarden" },
            {"subtext" : "alice in chains" },
            {"subtext" : "dio" }
        ]
    }
} 

post test/_search
{
    "fields": [
       "text"
    ]
}

Results

{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test",
            "_type": "test",
            "_id": "1",
            "_score": 1,
            "fields": {
               "text": [
                  "hello",
                  "soundgarden",
                  "alice in chains",
                  "dio"
               ]
            }
         }
      ]
   }
}