"Stateful" persistence in a Fusion JavaScript Pipeline - Capture Club
kmcowan 5 May, 2018 0

"Stateful" persistence in a Fusion JavaScript Pipeline

screenshot-2018-05-05-13-03-09

One of the most useful features of Nashorn JavaScript in Lucidworks Fusion is the ability to access Java objects within the context of your JavaScript stage. Often times, you’ll want to maintain the state of a variable; or maybe you want to only make a REST call once, and store the result.

You can certainly do this in a JavaScript stage.

Stage 1:

function(doc){
    var System = java.lang.System;
    if(System.getProperties().get("stateful_key") == null){
    System.getProperties().put("stateful_key", "foobar");
    logger.info("SET stateful key foobar");
    } else {
       logger.info("NOT SETTING stateful key... already set");
    }
    return doc;
}

So here we’ve grabbed the native Java System class, and set our own property “stateful_key”. Now if we have a second JavaScript stage down the line, we can reference that key:

Stage 2:

function(doc){
      var System = java.lang.System;
  if(System.getProperties().get("stateful_key") != null){
    var val = System.getProperties().getProperty("stateful_key")
    logger.info("GET stateful key "+val);
  } else {
       logger.warn("STATEFUL KEY NOT FOUND IN STAGE 2");
  }
    return doc;
}

If you run this in your Fusion instance, you’ll see that our key is stored and retrieved. This works as well were we to want to make a function call, load a file, run a query, or anything else. It’s a handy way to control the flow and customize your pipeline at the same time!

Leave a Reply

Your email address will not be published. Required fields are marked *