How to retrieve a field value from inner_hits filtered object

I was struggling with this as well as I needed to boost my query score as a function of a field within inner hits. Per the following post, inner hits are not accessible within scripts:

Bummer.

However, I managed to find a solution to my problem by using a nested query with a function score query inside it computing the score contribution of the nested hit.

For example, if you have the following mapping:

{
    "properties": {
        "field": {
            "type": "nested",
            "properties": {
                 "nested_field": {
                     "type": "text"
                 },
                 "nested_field_score": {
                     "type": "float"
                 }
            }
        }
    }
}

Then you can do the following nested query:

{
    "query": {
        "nested": {
            "path": "field",
            "query": {
                "function_score": {
                    "query": {
                        "match": {
                            "field.nested_field": "<match text>"
                        }
                    }
                },
                "script_score": {
                    "script": "doc['field.nested_field_score'].value"
                }
            }
        }
    }
}

You can then wrap this in a bool query and match non-nested fields along-side nested fields, each contributing a computed score.

This doesn't solve all issues with not having access to inner hits but worked well in my case.

1 Like