在Elstic Search中按字段长度对查询进行排序

时间:2019-05-15 00:19:14

标签: python elasticsearch

我的每个文档中都有一个字段,

'some_field': 3, 5, 10

但是每个文档都可以有非常长的数字,

'some_field': 3, 5, 10        # Doc 1
'some_field': 5               # Doc 2
'some_field': 3, 5, 10, 20, 9 # Doc 3

是否有一种按长度查询和排序的方法,这样我的结果就可以这样排列:

'some_field': 3, 5, 10, 20, 9 # Doc 3
'some_field': 3, 5, 10        # Doc 1
'some_field': 5               # Doc 2

我当前的查询,目前按_id排序

es_object.search(index='index', size=500, body={
            "sort": [
                {"_id": "desc"}
            ],
            "query": {

            "bool": {
                "must": [
                    {
                        "match_all": {}
                    },
                    {
                        "exists": {
                            "field": "some_field"
                        }
                    }
                ],
                "filter": [],
                "should": [],
                "must_not": []
            }
        }})

1 个答案:

答案 0 :(得分:1)

您可以执行脚本排序

{
    "sort": {
        "_script": {
            "script": "doc['some_field'].value.length()",
            "type": "number",
            "order": "asc"
        }
    },
    "query": {

        "bool": {
            "must": [{
                    "match_all": {}
                },
                {
                    "exists": {
                        "field": "some_field"
                    }
                }
            ],
            "filter": [],
            "should": [],
            "must_not": []
        }
    }
}