Elasticsearch查询按特定顺序按字段排序

时间:2016-02-29 16:03:13

标签: elasticsearch

我使用elasticsearch 2.2

我有一些索引类似的文件:

{     
  "id": 2116,
  "brand": "The Brand 1",
  "reference": "OI444",
  "supplier": "My supplier 1"
},
{     
  "id": 2118,
  "brand": "The Brand",
  "reference": "OI44488",
  "supplier": "My supplier"
}

我如何请求索引获取按id列表排序的查询,此查询有效,但以其他顺序返回结果。

{
  "query": {
    "bool": {
      "filter": {
        "ids": {
          "values": [
            2118, 2116
          ]
        }
      }
    }
  }
}

在我的情况下,我的id列表可以是随机的,如216,105,208,我需要在结果集中遵守此顺序

1 个答案:

答案 0 :(得分:1)

  • 您使用的字段不应在映射中进行分析
  • 添加排序

查询

POST c1_2/Test/_search/
{
  "sort": [
    {
      "_script": {
        "script": "doc['id'] != null ? sortOrder.indexOf(doc['id'].value.toInteger()) : 0",
        "type": "number",
        "params": {
          "sortOrder": [
            2116,
            211
          ]
        },
        "order": "desc"
      }
    },
    "_score"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "brand": [
              "The"
            ]
          }
        },
        {
          "ids": {
            "values": [
              2118,
              2116,
              211
            ]
          }
        }
      ]
    }
  }
}
相关问题