Modifying response

We have a need to modify the response document(s) from a query before returning it to the user.
For example, we might need to rename a document field to a more user-friendly name.

I understand that elasticsearch has extensions or other means of doing this. So if anyone can point me in the right direction, i would greatly appreciate it.

thanks

Painless Script is an option:

{
    "query" : {
        "match_all": {}
    },
    "script_fields" : {
        "alias_field" : {
            "script" : {
                "source": "doc['name.keyword'].value"
            }
        }
    }
}
1 Like

Thank you for your reply. Much appreciate it.
I’m sorry but I must not be getting it, because when I read the docs in painless APIs it seems to work for values of fields VS actual field names...but the Painless APIs might be the right answer and I am not getting it.
Can you confirm how I can change the field name in a source doc, say from “random_field_name” to “friendly_field_name”

Thanks

This create a script field 'friendly_field_name' to replace field 'random_field_name' in source doc:

  {
        "query" : {
            "match_all": {}
        },
        "script_fields" : {
            "friendly_field_name" : {
                "script" : {
                    "source": "doc['random_field_name.keyword'].value"
                }
            }
        }
    }

And it returns like:

{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "test2",
        "_type": "doc",
        "_id": "2",
        "_score": 1,
        "fields": {
          "friendly_field_name": [
            "abc"
          ]
        }
      },
      {
        "_index": "test2",
        "_type": "doc",
        "_id": "1",
        "_score": 1,
        "fields": {
          "friendly_field_name": [
            "abc"
          ]
        }
      }
    ]
  }
}

As far as I know you can not change the source returned.

Thanks
if i am understand your, this script will be added to the _search endpoint and it will ADD new scripted field in the response, called "friendly_field_name" but the old field "random_field_name" will still be there too?

If that is true, is there a way just to rename the field with a script without adding a new field?

the old field "random_field_name" will still be there too?

The old field will not be in response.

is there a way just to rename the field with a script without adding a new field

The source can not be changed. The option I have learned is adding a new script field using Painless Script.

@wangqinghuan this is awesome. Thanks.
Where r u located? Are you interested in freelance work? We could use someone like you on our team.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.