Knowledgebase:

How to work with datasets in Ignition

Posted by Peggie Wong, Last modified by Anna Christian on 10/13/2017 03:21 PM

In Ignition you use datasets in both Event Scripts and Expression bindings all the time. You often want to fetch specific values from the dataset but the syntax for the two is different and it is not uncommon to confuse them. This article will go over how to use each of them appropriately.

Using Datasets in Expression Bindings

Using a dataset in an Expression binding is very straightforward. You want to take the dataset property, then index into it with 1 set of square brackets ([]) to return an object. You can cast the result to make it return the correct datatype.

Assuming this is your dataset:

ID NAME VALUE
1 abc 13.2
2 def 4.9
{Root Container.path.to.component.datasetName}[0,1]
//returns an object with "abc"

{Root Container.path.to.component.datasetName}[0,"NAME"]
//returns an object with "abc"

{Root Container.path.to.component.datasetName}[0,"NAME"])
//returns the string "abc"

toFloat({Root Container.path.to.component.datasetName}[0,2])
//returns the float 13.2

toFloat({Root Container.path.to.component.datasetName}[2,2])
//returns an error because there is no row at position 2 (no 3rd row). 
//You can use the try() function to prevent this error. It is common for a dataset to have 0 
//rows in it while it is reloading, so it is good practice to always include the try() function.

try(toInt({Root Container.path.to.component.datasetName}[2,0]),-1)
//returns -1 because there is no row at position 2

try(toInt({Root Container.path.to.component.datasetName}[0,0]),-1)
//returns 1

Using Datasets in Event Scripts

Using a dataset in an Event Script is a little more complicated for two reasons.

  1. In scripting, a dataset is a list of lists.
  2. There is a difference between an Ignition dataset and a Python Dataset.

To access a single element, you need to fetch the dataset property, convert it into a Python dataset, then index into it with 2 sets of square brackets "[]" to return a value.
Assuming the same dataset:

ID NAME VALUE
1 abc 13.2
2 def 4.9
# get the Ignition dataset
dataset = event.source.datasetName

# convert the Ignition dataset to a Python dataset
pythonDataset = system.dataset.toPyDataSet(dataset)

# get the first element of the first row.
# This can be done in two ways, by using the firstRow variable, or directly.
# Note that val1 and val2 are the same.

val1 = pythonDataset[0][0]

# get the first row of the python Dataset
firstRow = pythonDataset[0]
val2 = firstRow[0]

# because you can access a row with just one set of square brackets, you can use a for loop to easily step through a dataset.
# this will print out 13.2 and then 4.9
for row in pythonDataset:
    print row[2]

# convert the Python dataset into an Ignition dataset to put it into a component's property
event.source.datasetName = system.dataset.toDataSet(pythonDataset)
(25 vote(s))
Helpful
Not helpful