Philip David
Philip David

Reputation: 11

elasticsearch multi field sort script

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
                        }

                }
            ]

Upvotes: 1

Views: 1696

Answers (1)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5899

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.

Upvotes: 1

Related Questions