Elasticsearch:按字段排序,最后为空值

时间:2015-04-18 08:49:07

标签: elasticsearch

我希望按name排序,但在结果的末尾保留带有空或缺少price数据的条目。

我试过了:

sort: {
    sorting.name: {
        order: "asc"
    },
    prices.minprice.price: {
        missing: "_last"
    }
}

但这仅按名称排序。

3 个答案:

答案 0 :(得分:5)

为此,我们可以使用自定义函数分数(which is faster than custom script based sorting according to elasticsearch documentation)。当价格缺失时,数值将返回0.

然后,我们首先对得分进行排序,将其拆分为缺少价格数据的部分,以及不丢失价格数据的部分,然后根据名称对这两个部分进行排序。

{
    "query": {
        "function_score": {
            "boost_mode": "replace",
            "query": {"match_all": {}},
            "script_score": {
                "script": "doc['price'].value == 0 ? 0 : 1"
            }   
        }
    },
    "sort": [
       "_score",
       "name"
    ]
}

答案 1 :(得分:1)

这对我有用,

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_script_based_sorting

"sort":[
      {
         "_script":{
            "type":"number",
            "script":{
               "lang":"painless",
               "source":"return params._source.store[0].sku_available_unit == 0 ? 0 : 1;"
            },
            "order":"desc"
         }
      }
    ]

答案 2 :(得分:1)