How to get term position in sort script

In Elasticsearch 8, I have the following index:

{
    "settings": {
        "analysis": {
            "analyzer": {
                "default": {
                    "type": "whitespace"
                },
                "default_search": {
                    "type": "whitespace"
                }
            }
        }
    },
    "mappings": {
        "properties": {
            "title": {
                "type": "text",
                "term_vector": "with_positions"
            }
        }
    }
}

And this query

{
    "query": {
        "simple_query_string": {
            "query": "banana"
        }
    },
    "track_scores": true,
    "sort": {
        "_script": {
            "type": "number",
            "order": "desc",
            "script": {
                "source": " >>> HOW TO GET THE POSITION OF banana IN THE title FIELD? <<< ",
                "lang": "painless"
            }
        }
    }
}

I found very old answers, such as:
_index['title'].get('banana',_POSITIONS);
But that errors:
cannot resolve symbol [_index]

I need this because I want higher score for documents where the query appears earlier in the title field.

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