1

I'm having trouble doing multi-field sort script in elasticsearch , for example I want to sort by field A desc, field B desc. When I do the script with two sort it is doing sort only by field B desc.

            'sort': [
                {

                    '_script' : {
                        'script' : 'if (doc['+'\''+sortColumn1+'\''+'].value==null) {return '+'\''+'\''+'} else {return doc['+'\''+sortColumn1+'\''+'].value} ',
                        'type' : sortType1,
                        'order' : sortOrder1,
                    },
                    '_script' : {
                        'script' : 'if (doc['+'\''+sortColumn2+'\''+'].value==null) {return '+'\''+'\''+'} else {return doc['+'\''+sortColumn2+'\''+'].value} ',
                        'type' : sortType2,
                        'order' : sortOrder2
                        }

                }
            ]

1 Answer 1

1

According to the official documentation for script sorting your JSON would have to looke like this:

'sort': {
    '_script' : {
        'script' : 'if (doc['+'\''+sortColumn1+'\''+'].value==null) {return '+'\''+'\''+'} else {return doc['+'\''+sortColumn1+'\''+'].value} ',
        'type' : sortType1,
        'order' : sortOrder1,
    },
    '_script' : {
        'script' : 'if (doc['+'\''+sortColumn2+'\''+'].value==null) {return '+'\''+'\''+'} else {return doc['+'\''+sortColumn2+'\''+'].value} ',
        'type' : sortType2,
        'order' : sortOrder2
    }
}

And it's clear why sorting does only work for field B. Because you override the key _script and the last one is the one which is taken into effect. So you can only define one _script to sort your result.

So you have to combine those two into one somehow.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.