如何在elasticsearch中按字段排序?

时间:2017-05-28 11:42:31

标签: sorting elasticsearch

我有一个像这样的mysql查询:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts 
WHERE 1=1 
AND wp_posts.ID IN (2991,2993,2989,2983,2987)
AND wp_posts.post_type = 'product'
AND ((wp_posts.post_status = 'publish')) 
ORDER BY FIELD( wp_posts.ID, 2991,2993,2989,2983,2987 )
LIMIT 0, 10

我想注意具体的一句话:
ORDER BY FIELD( wp_posts.ID, 2991,2993,2989,2983,2987 )

在elasticsearch中,我们只能按ascdesc排序:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_sort_order

所以任何人都可以指出如何在弹性搜索查询中实现order by field (id, x,y,z)

1 个答案:

答案 0 :(得分:1)

它不像SQL那么容易,但您可以使用function_score和多个match es作为您的值。
像这样的东西:

{
   "query": {
      "function_score": {
         "query": {
            "bool": {
               "must": [
                  {
                     "terms": {
                        " ID": [
                           2991,
                           2993,
                           2989,
                           2983,
                           2987
                        ]
                     }
                  },
                  {
                     "term": {
                        "post_type": {
                           "value": "product"
                        }
                     }
                  },
                  {
                     "term": {
                        "post_status": {
                           "value": "publish"
                        }
                     }
                  }
               ]
            }
         },
         "boost": "5",
         "functions": [
            {
               "filter": {
                  "match": {
                     "ID": 2991
                  }
               },
               "weight": 100
            },
            {
               "filter": {
                  "match": {
                     "test": 2993
                  }
               },
               "weight": 99
            },
            {
               "filter": {
                  "match": {
                     "test": 2989
                  }
               },
               "weight": 98
            },
            {
               "filter": {
                  "match": {
                     "test": 2983
                  }
               },
               "weight": 97
            },
            {
               "filter": {
                  "match": {
                     "test": 2987
                  }
               },
               "weight": 96
            }
         ],
         "score_mode": "max",
         "boost_mode": "multiply"
      }
   }
}