如何按弹性搜索中的计算值排序

时间:2016-04-08 13:22:57

标签: sorting elasticsearch

我想将elasticsearch用作搜索引擎。我正在将记录从mysql复制到elasticsearch,当我查询elasticsearch时,我想用弹性数据计算一个值并用它来对结果进行排序

我的索引如下:

  {
    "busquedas" : {
      "aliases" : { },
      "mappings" : {
        "coche" : {
          "properties" : {
            "coeff_e" : {
              "type" : "double"
            },
            "coeff_r" : {
              "type" : "double"
            },
            "desc" : {
              "type" : "string"
            }
          }
        }
      },
      "settings" : {
        "index" : {
          "creation_date" : "1460116924258",
          "number_of_shards" : "5",
          "number_of_replicas" : "1",
          "uuid" : "N6jhy_ilQmSb6og16suZ4g",
          "version" : {
            "created" : "2030199"
          }
        }
      },
      "warmers" : { }
    }

}

我想计算每条记录的值,如

myCustomOrder = (coeff_e + coeff_r) * timestamp

并使用它来对结果进行排序

{
  "sort" : [
      { "myCustomOrder" : {"order" : "asc"}},
      "_score"
  ],
  "query" : {
      "term" : { ... }
  }
}

我知道我可以使用groovy来计算值,但我只能使用它来过滤,就像示例中所示

{
  "from": 10,
  "size": 3,
  "filter": {
    "script": {
      "script": "doc['coeff_e'].value < 0.5"
    }
  }
}

提前谢谢你,我是弹性搜索的新手:D

1 个答案:

答案 0 :(得分:1)

与过滤相同。看一下这个section of the documentation。一旦你已经了解了脚本,它应该是不言自明的: - )。

为了完整起见:

{
    "query" : {
        ....
    },
    "sort" : {
        "_script" : {
            "type" : "number",
            "script" : {
                "inline": "doc['field_name'].value * factor",
                "params" : {
                    "factor" : 1.1
                }
            },
            "order" : "asc"
        }
    }
}