Search code examples
elasticsearch-5elasticsearch-painless

elasticsearch with painless script to return extra fields


I am following this example https://www.compose.com/articles/how-to-script-painless-ly-in-elasticsearch/ where BOTH the ORIGINAL fields plus the calculated field (some_scores) are presented in the result document.

{
    "_index": "sat",
    "_type": "scores",
    "_id": "AV3CYR8JFgEfgdUCQSON",
    "_score": 1,
    "_source": {
        "cds": 1611760130062,
        "rtype": "S",
        "sname": "American High",
        "dname": "Fremont Unified",
        "cname": "Alameda",
        "enroll12": 444,
        "NumTstTakr": 298,
        "AvgScrRead": 576,
        "AvgScrMath": 610,
        "AvgScrWrit": 576,
        "NumGE1500": 229,
        "PctGE1500": 76.85,
        "year": 1516
    },
    "fields": {
        "some_scores": [
            1152
        ]
    }
}

Now i am doing a _search with the following post body

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "some_scores": {
      "script": {
          "lang": "painless",
        "inline": "\"hello\""
      } 
    }
  }
    }

but the results i am getting DOESN'T contain the original fields; it only contains the testing field which i hardcoded to hello. Is there anything wrong with my query ?

"hits": [
        {
            "_index": "abcIndex",
            "_type": "data",
            "_id": "id_00000025",
            "_score": 1.0,
            "fields": {
                "some_scores": [
                    "hello"
                ]
            }
        }]

Solution

  • You need to explicitly pass _source": ["*"] when using script field. I was not able to find reason for this , looks like some kind of optimization.

    {
      "_source": ["*"],
      "query": {
        "match_all": {}
      },
      "script_fields": {
        "some_scores": {
          "script": {
            "lang": "painless",
            "inline": "doc['authorization']+\"hello\""
          }
        }
      }