介绍
Apache NiFi是一个流数据系统,它提供了强大的数据流处理能力,可以实现数据的实时收集、转换和传输。其中,ExecuteScript处理器是NiFi中一个非常有用的处理器,它允许用户通过脚本执行自定义逻辑来处理数据流。本文将探讨如何使用NiFi ExecuteScript处理器结合Python脚本,来修改FlowFile的内容以及属性,以实现灵活的数据流处理任务。
Python在NiFi中的应用
NiFi选择支持Python作为执行脚本的语言,这是因为Python具有简单易用、功能强大、生态丰富等优点,同时可以满足大多数用户的需求。通过Python脚本,用户可以轻松地实现复杂的数据处理逻辑,并且可以利用Python丰富的第三方库来完成各种数据处理任务。
ExecuteScript处理器配置
在NiFi中配置ExecuteScript处理器需要指定使用的脚本语言、脚本文件路径等参数。在我们的例子中,我们将选择Python作为脚本语言,并提供一个指向我们Python脚本文件的路径。确保脚本文件具有适当的权限,并且可以被NiFi执行。
案例:修改FlowFile内容
以下的例子是在ExecuteScript中用Python对输入的Flowfile的内容进行修改,Flowfile的内容是JSON数据,我们将读取这个JSON,并且添加新的属性然后再进行输出。
拓扑图:
GenerateFlowFile处理器配置:
Flowfile的内容为:
{
"FirstName":"Bob",
"LastName":"Ryan"
}
ExecuteScript处理器配置:
Scirpt Body如下:
import json
import sys
import traceback
from java.nio.charset import StandardCharsets
from org.apache.commons.io import IOUtils
from org.apache.nifi.processor.io import StreamCallback
from org.python.core.util import StringUtil
from datetime import datetime
class TransformCallback(StreamCallback):
def __init__(self,flowFile):
self.flowFile = flowFile
def process(self, inputStream, outputStream):
try:
# Read input FlowFile content
input_text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
#Transform the input string into JSON object
input_obj = json.loads(input_text)
#Add age attribute
input_obj['Age'] = 26
#Transform the JSON object into string
output_text = json.dumps(input_obj)
#Output the result
outputStream.write(StringUtil.toBytes(output_text))
except:
traceback.print_exc(file=sys.stdout)
raise
flowFile = session.get()
if flowFile != None:
try:
callback = TransformCallback(flowFile)
flowFile = session.write(flowFile, callback)
session.transfer(flowFile, REL_SUCCESS)
except Exception as e:
# Catch the exception and set it as an attribute
session.putAttribute(flowFile, "error", 'An error occurred, due to ' + str(e))
session.transfer(flowFile, REL_FAILURE)
输出的结果为:
{"FirstName": "Bob", "LastName": "Ryan", "Age": 26}
总结
ExcuteScript是一个强大的处理器,结合Python脚本可以对Flowfile的content进行修改,生成业务需要的数据。