Handling Optional or Repeating Segments

There are a couple helpful strategies for dealing with optional and repeating segments.

Here’s an example HL7 message:

MSH|^~\&|AcmeMed|E\T\R|Main HIS|St. Micheals|20110213145956||ADT^A07|9B38584DCB03B0577D55CF66983BA79B39022ABD61F9E0188DD9BD03B2C99446|P|2.6| EVN||20110213144818||||20110213144552| PID|||2495499^^^ADT1||Meade^Sabrina||20001005|F||Martian|207 Miller Lane^^Toronto^ON^16200|||||||7-264-942|365-5-488| NK1|1|Garland^Sabrina|Second Cousin| NK1|2|Smith^Fred|Grandchild| NK1|3|WHITE^Tracy|Grandchild| NK1|4|Fitzgerald^John|Grandchild| NK1|5|Adams^Mary|Parent| PV1||E||||||5101^WHITE^Tracy^F^^DR|||||||||||602131^^^ADT1|||||||||||||||||||||||||20110213150128|

If we take a look at a VMD for an ADT message, we’ll see that the NK1 segment can be both optional and repeating.

How would we map this message to a database containing two tables, a Patient and Kin table?

If you’d like to try this out in the Translator, create a custom component and use the following files:

function main(Data) local msg, name = hl7.parse{vmd='adt.vmd', data=Data} local outboundTable = db.tables{vdb='patients.vdb'} if name == 'ADT' then processADT(outboundTable, msg) end end function mapPatient(T, PID) T.id = PID[3][1] T.firstName = PID[5][2] T.lastName = PID[5][1][1] T.birthdate = PID[7] end function mapKin(T, NK1) if not NK1:isNull() then T.firstName = NK1[2][2] T.lastName = NK1[2][1][1] T.relationship = NK1[3][1] end end function processADT(T, msg) for i=1, #msg.NK1 do mapPatient(T.Patients[1], msg.PID) mapKin(T.Kin[i], msg.NK1[i]) end trace(T) end

See the repeated segments captured in the parsed HL7 message.

Using a for loop and the # Operator on Userdata Objects, we can count the NK1 segments and loop through each segment, starting at the first, to pass each segment to mapKin to be mapped to our database Kin table.

Using if statements and node:isNull(), we can add logic to say “if NK1 exists, (is not null), then map the following fields into the table.”

You can confirm the mappings by clicking on trace(T) in the annotations to see the resulting database Patient and Kin tables.