ElasticSearch:基于父嵌套字段的组合对文档进行排序

时间:2016-04-14 00:44:17

标签: elasticsearch elasticsearch-2.0

我正在尝试通过将根文档中找到的数字字段与嵌套文档中找到的字段组合来对ES文档进行排序。为简单起见,我想说我想对doc['score'] + doc['nested.score']进行排序。

示例映射和几个数据文档在此处:http://pastebin.com/9sdMphsR

尝试直接访问doc['score']时的一种天真(和错误)方法是:

POST /testing/stuff/_search
{
    "query": {
        "match_all": {
        }
    },
    "sort": {
        "_script": {
            "type": "number",
            "mode": "max",
            "script": {
                "inline": "doc['score'].value + doc['variations.score'].value",
                "lang": "expression"
            },
            "order": "desc",
            "nested_path": "variations"
        }
    }
}

这样做的正确方法是什么?我意识到我可以将根级score复制到每个嵌套文档中,但如果我可以避免这样做,我宁愿这样做。

1 个答案:

答案 0 :(得分:0)

POST /testing/stuff/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "inline": "def max=java.lang.Integer.MIN_VALUE; for(obj in doc['variations.score']){ if (obj > max) max = obj; }; return doc['score'].value + max",
        "lang": "groovy"
      },
      "order": "desc"
    }
  }
}

variations字段需要"include_in_parent": true才能使脚本能够访问嵌套值。