Search code examples
javascriptapache-nifiexecute-script

NiFi how do I pass an attribute to the executeScript processor


The flowfile uses evaluateJsonPath in order to extract values and setup my Attributes. I need to pass some of the attributes into a JavaScript function which I have in a ExecuteScript processor. The setting is for ECMAScript and the JS code is in the Script Body.

So, as an example if my attributes are A, B, C and my function is foo(arg){}

How do I call the function foo(A)?

I have tried putting at the end of the Script Body, after the declaration of my function foo

foo(A);
foo(${A});

But this keeps failing and I am not able to find any examples on how to pass in the value to the function call. I get either a "A is not defined in " or Expects a , and got a {.

What is the proper way to pass an Attribute to the ExecuteScript processor?

UPDATED: SEE BELOW

So as I'm trying to figure this out here is what I'm dealing with.

  1. Read in a JSON file
  2. Set some attributes with EvaluateJSONPath
  3. HERE I NEED TO merge some attributes and want to use the ExecuteScript to run some JavaScript

JAVASCRIPT

var flowFile = session.get();
if(flowFile){
  var argFoo = flowFile.getAttribute("someAttribute");
  
  // Set the value as a new Attribute in the flowFile
  session.putAttribute(flowFile, "NewAttribute", argFoo);
}

I've also tried things like

var flowFile = session.get();
if(flowFile){
  var argFoo = flowFile.getAttribute("someAttribute");

  // Create a new flowFile
  var newFlowFile = session.create(flowFile);
  // Set the value as a new Attribute in the flowFile
  session.putAttribute(newFlowFile, "NewAttribute", argFoo);
}

I'm blindly guessing how to get this to work.

Can someone point me in the right direction here on how to use JavaScript within this ExecuteScript processor?

The latest error is "This FlowFile was not created in this session and was not transferred to any Relationship via ProcessSession.transfer()"


Solution

  • Check these sites:

    You don't have to create new a FlowFile, if you want only to add a new attribute.

    Example

    flowFile = session.get();
    if (flowFile != null) {
    
        // Get attributes
        var greeting = flowFile.getAttribute("greeting");
        var message = greeting + ", Script!";
    
        // Set single attribute
        flowFile = session.putAttribute(flowFile, "message", message);
    
        // Set multiple attributes
        flowFile = session.putAllAttributes(flowFile, {
            "attribute.one": "true",
            "attribute.two": "2"
        });
    
        session.transfer(flowFile, REL_SUCCESS)
    }