elasticsearch query by array of id 返回结果不按传入的id数组排序

elasticsearch query by array of id result returned is not sorted by the array of id pass in

我正在使用 elastica,以下是我的查询:

    $query = new Query();

    $query->setSize(5);

    $qb = new \Elastica\Query\Ids();

    $qb->addId("id_5");
    $qb->addId("id_3");
    $qb->addId("id_4");
    $qb->addId("id_1");
    $qb->addId("id_2");

    return $query->setQuery($qb)

我希望结果 return 与我传入的顺序相同,例如在这种情况下它将是 "id_5, id_3, id_4, id_1, id_2"

然而我得到的排序与我想要的不一样

我认为这是两个解决方案 1. 如果你有 id 作为文档的一部分,那么你可以做

POST indexName/_search
{
  "sort": [
    {
      "_script": {
        "type": "number",
        "script": "sortOrder.indexOf(doc['Id'].value)",
        "params": {
          "sortOrder": [
            "AVMX9sHTyNVr4SjF3oRt",
            "AVMTc1fSyNVr4SjF3WpF",
            "AVMYuGLOyNVr4SjF3rKm"
          ]
        },
        "order": "asc"
      }
    }
  ],
  "query": {
    "ids": {
      "values": [
        "AVMX9sHTyNVr4SjF3oRt",
            "AVMTc1fSyNVr4SjF3WpF",
            "AVMYuGLOyNVr4SjF3rKm"
      ]
    }
  }
}

如果不是,那么您需要将您的类型的映射更新为

{
  "mappings": {
    "YOUR_TYPE": {
      "_id": {
        "index": "not_analyzed"
      }
    }
  }
}

那么你可以使用"script":"sortOrder.indexOf(doc['_id'].value)"