# How to get term position in sort script

**URL:** <https://discuss.elastic.co/t/how-to-get-term-position-in-sort-script/356555>\
**Category:** Elasticsearch\
**Tags:** painless\
**Created:** [April 1, 2024, 12:29pm UTC](https://discuss.elastic.co/t/how-to-get-term-position-in-sort-script/356555 "2024-04-01T12:29:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![skaccer](https://avatars.discourse-cdn.com/v4/letter/s/b19c9b/32.png) [@skaccer](https://discuss.elastic.co/u/skaccer)\
**Post date:** [April 1, 2024, 12:29pm UTC](https://discuss.elastic.co/t/how-to-get-term-position-in-sort-script/356555/1 "2024-04-01T12:29:23Z")

</div>

In Elasticsearch 8, I have the following index:

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

```

And this query

```auto
{
    "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.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [April 29, 2024, 12:29pm UTC](https://discuss.elastic.co/t/how-to-get-term-position-in-sort-script/356555/2 "2024-04-29T12:29:40Z")

</div>

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