Search code examples
javajsonapache-nifitransformationjolt

Conditional Jolt Transform


I want to write a jolt transform that places the value of coordinates into a single array "coordinates" if the type is Polygon, and into properties "x", "y", "z" if the type is Point. I think I am close with my current spec, but am not sure beyond trying different values after the &.

Input Json1

{
  "features": [
    {
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              11.1,
              111.1
            ],
            [
              22.2,
              222.2
            ],
            [
              33.3,
              333.3
            ]
          ]
        ]
      }
    }
  ]
}

Input Json2

{
  "features": [
    {
      "geometry": {
        "type": "Point",
        "coordinates": [
          1.1,
          2.2,
          3.3
        ]
      }
    }
  ]
}

Spec

[
  {
    "operation": "shift",
    "spec": {
      "features": {
        "*": {
          "geometry": {
            "type": {
              "Polygon": {
                "coordinates": {
                  "*": "[&4].coordinates"
                }
              },
              "Point": {
                "coordinates": {
                  "0": "[&4].x",
                  "1": "[&4].y",
                  "2": "[&4].z"
                }
              }
            }
          }
        }
      }
    }
  }
]

Expected output: Point

[ {
  "x" : 1.1,
  "y" : 2.2,
  "z" : 3.3
} ]

Expected output: Polygon

[ {
  "coordinates" : [ [ 11.1, 111.1 ], [ 22.2, 222.2 ], [ 33.3, 333.3 ] ]
} ]

I tried the above spec, and am expecting to get the output showing either an object of coordinates or x,y,z. I am able to get it to work each case individually when I replace [&4] with [&3] and remove the conditional casing, but with it, I know there are some intricacies with levels that I am not handling correctly.


Solution

  • You need to reference back to the value of the coordinates after the type key value which is 2 level up @(2,coordinates) :

    [
      {
        "operation": "shift",
        "spec": {
          "features": {
            "*": {
              "geometry": {
                "type": {// level 2 where coordinates is located 
                  "Polygon": {
                    "@(2,coordinates)": {
                      "*": "[&5].coordinates"
                    }
                  },
                  "Point": { //level 1
                    "@(2,coordinates)": { // level 0
                      "0": "[&5].x",
                      "1": "[&5].y",
                      "2": "[&5].z"
                    }
                  }
                }
              }
            }
          }
        }
      }
    ]