ElasticSearch 按正则表达式排序

ElasticSearch sorting by regexp

我在 ElasticSearch 6 索引中有一个可以与正则表达式匹配的字段。我需要对搜索结果进行排序,以便具有匹配值的文档排在那些不匹配的文档之前。有什么方法可以在排序子句中使用正则表达式吗?

示例文档:

 "mappings" : {
  "unit" : {
    "properties" : {
      "description" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
  }

我考虑过这样的脚本排序:

  "sort" : {
    "_script" : {
        "type" : "number",
        "script" : {
            "source": "regex('some_regexp_here').match(doc['description'].value) ? 1 : 0 ",
        },
        "order" : "desc"
      }
   }

可能吗?还有其他解决方法吗?谢谢。

我想通了。排序子句应该是这样的:

"sort": {
  "_script": {
    "order": "desc",
    "type": "number",
    "script": {
      "source": 
         "def m = /my_regex_here/.matcher(doc['description'].value);
          if(m.matches()) {
            return 1
          } else {
            return 0
          }"
    }
  }
}

请注意,正则表达式两边的“/”符号是必需的。