如何在AWS ElasticSearch的无痛内联脚本中使用regexp替换字符串?

时间:2017-12-07 15:15:34

标签: elasticsearch elasticsearch-painless

"等级的类型"文档中的字段已从"关键字"更改到"短"并且我试图重新索引存在的数据,以便能够在Kibana图表中使用它。 旧数据包含以下值:" 100%","错误"或者只是空字符串""。

我想在新索引中只获取整数。我使用内部reindex API(添加新行以使代码段更具可读性):

curl -s -X POST -H 'Content-Type: application/json' https://search-host.us-east-1.es.amazonaws.com/_reindex -d '{
  "source": {
    "index": "old-index"
  },  
  "dest": {
    "index": "new-index"
  },  
  "script": {
    "inline": "
        if (ctx._source.level == \"error\" || ctx._source.level == \"\")
        {
            ctx._source.level = -1
        } else {
            ctx._source.level = Integer.valueOf(ctx._source.level)    )
        }
    "
  }
}'

但是我收到了错误:" java.lang.String无法转换为java.lang.Number"因为"%"价值结尾处的符号。

此外,我没有为AWS ElasticSearch启用正则表达式,并且我无法按照我的想法执行此操作。所以使用replaceAll的变体对我来说并不起作用。如果我有自托管的ES,例如它可能是这样的(没有测试它):/(%)?/.matcher(doc['level'].value).replaceAll('$1')

但是从AWS ES我看到了:

Regexes are disabled. Set [script.painless.regex.enabled] to [true] in elasticsearch.yaml to allow them. Be careful though, regexes break out of Painless's protection against deep recursion and long loops.

是否可以在没有正则表达式的情况下用无痛语言替换字符串?

2 个答案:

答案 0 :(得分:1)

我试图做同样的事情,我最终会在我的一个索引中的字符串字段中进行完整查找和替换。不幸的是,对我来说,我也无法访问RegEx。

这是我提出的解决方案,使用如下所示的摄取管道:

PUT _ingest/pipeline/my-pipeline-id
{
    "description": "Used to update in place",
    "processors": [
        {
            "grok": {
                "field": "myField",
                "patterns": ["%{PART1:field1}%{REMOVAL}%{PART2:field2}"],
                "pattern_definitions": {
                    "PART1": "start",
                    "REMOVAL": "(toRemove){0,1}",
                    "PART2": ".+"
                },
                "ignore_missing": true
            }
        },
        {
            "script": {
                "lang": "painless",
                "inline": "ctx.myField = ctx.field1 + ctx.field2"
            }
        },
        {
            "script": {
                "lang": "painless",
                "inline": "ctx.remove('field1'); ctx.remove('field2')"
            }
        }
    ]
}

然后你运行它(我已经使用查询更新完成了它)

POST /index/type/_update_by_query?pipeline=my-pipeline-id
{
    "query": {
        "match": {
            "id": "123456789"
        }
    }
}

有用的链接

请注意

我正在使用ES 5.5。对于版本6,某些语法已更改,但过程保持不变。

答案 1 :(得分:1)

"script": {
    "lang":"painless",
    "source": """

      //function declaration
      String replace(String word, String oldValue, String newValue) {
        String[] pieces = word.splitOnToken(oldValue);
        int lastElIndex = pieces.length-1;
        pieces[lastElIndex] = newValue;
        def list = Arrays.asList(pieces);
        return String.join('',list);
      }

      //usage sample
      ctx._source["date"] = replace(ctx._source["date"],"+0000","Z");

    """
}
相关问题