如何在NiFi中实现属性与外部多子串匹配并返回匹配值?
NiFi实现属性多子串匹配并生成新属性解决方案
针对你遇到的问题——需要匹配Flowfile属性与外部字典中的多子串,并将所有匹配项生成新属性,可通过ExecuteGroovyScript处理器实现,具体步骤如下:
1. 准备字典文件
保持字典文件为每行一个子串格式,清理冗余符号(如示例中的末尾逗号),最终内容如下:
A B
2. 配置ExecuteGroovyScript处理器
使用Groovy脚本完成字典加载、子串匹配、新属性生成的全流程,脚本示例如下:
import groovy.json.JsonSlurper import java.nio.file.Files // 从处理器属性读取字典文件路径(推荐配置为动态属性,便于更新) def dictPath = flowFile.getAttribute("dict.file.path") def dictLines = Files.readAllLines(new File(dictPath).toPath()) // 清理字典项:去除空行、末尾逗号、首尾空格 def dictTerms = dictLines.collect { it.trim().replaceAll(/,$/, "") }.findAll { it } // 读取Flowfile中的JSON内容,提取目标字段(若Name是属性则直接用getAttribute获取) def flowFile = session.get() if (!flowFile) return def content = session.read(flowFile) { inputStream -> new JsonSlurper().parse(inputStream) } def targetValue = content.Name ?: "" // 拆分目标值为子串列表 def splitValues = targetValue.split(",").collect { it.trim() } // 匹配字典项,生成Match1、Match2...属性 def matches = splitValues.intersect(dictTerms) matches.eachWithIndex { term, index -> flowFile = session.putAttribute(flowFile, "Match${index+1}", term) } session.transfer(flowFile, REL_SUCCESS)
处理器配置要点:
- 添加动态属性
dict.file.path,值为你的字典文件绝对路径(便于后续更新字典时无需修改脚本) - 若
Name是Flowfile的属性而非Content中的JSON字段,将脚本中提取targetValue的代码替换为:def targetValue = flowFile.getAttribute("Name") ?: ""
3. 运行验证
将示例Flowfile(内容为{"Name":"A,B"})传入处理器后,会生成两个新属性:
Match1: AMatch2: B
该方案支持任意数量的字典子串,更新字典仅需修改外部文件,无需调整处理器配置。
内容的提问来源于stack exchange,提问作者Fuzzorama17
相关产品推荐
相关产品推荐

