需求:在es的watcher中想使用chain input,第一个Input使用http input,然后对response中的数据进行部分截取作为第二个Input中的参数。官方提供的一种方法是在第一个input和第二个input中间加一个transform的script对数据进行处理再进入第二个input。但是这里我们想要分割字符串获取其中的某个值时,通常会使用split方法,但是在es的script中使用painless时,split使用了正则表达式,而es中默认是不开启正则表达式的,因为开启后会造成性能问题。所以结合业务需求,我们采用lastIndexOf的方法来截取字符串。
{
"trigger": {
"schedule": {
"interval": "10s"
}
},
"input": {
"chain": {
"inputs": [
{
"first": {
"http": {
"request": {
"scheme": "http",
"host": "xxxxxxxx",
"port": xxxx,
"method": "get",
"params": {},
"headers": {}
}
}
}
},
{
"second": {
"transform": {
"script": {
"source": "def myString = ctx.payload.first.city;def beginIdex = myString.lastIndexOf('-');def subString = myString.substring(beginIndex-3,beginIndex);return ['city' : subString];", //city是http response中的一个key,通过这种方式获取Json中对应的value. return的时候用我们的新值去覆盖原来的值
"lang": "painless"
}
}
}
},
{
"third": {
"search": {
"request": {
"search_type": "query_then_fetch",
"indices": [
"test_chain_index"
],
"types": [],
"body": {
"query": {
"bool": {
"filter": [
{
"term": {
"city_name": "{{ctx.payload.second.city}}" //city_name:要过滤的字段名
}
}
]
}
}
}
}
}
}
}
]
}
},
"condition": {
"compare": {
"ctx.payload.third.hits.total": {
"gt": 0
}
}
},
"actions": {
"log_error": {
"logging": {
"level": "info",
"text": "xxxxxxxxxxxx"
}
}
}
}