cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How do I use a value stored in a variable to access an element in an array?

Within my environment, I have hosts with various tags against them. I'm looking for a tag which contains:

DEPARTMENT:

 and this tag can be in index 5 or 4, it is random. 

Here is my code so far:

timeseries { percent = avg(dt.host.disk.used.percent), used = avg(dt.host.disk.used), avail = avg(dt.host.disk.avail) }, by: { dt.entity.host, dt.entity.disk }
| fieldsAdd Utilisation = arrayAvg(percent), entityName(dt.entity.disk)
| fieldsAdd entityName(dt.entity.host)
| lookup [ fetch dt.entity.host 
| fields id, tags[] ], sourceField:dt.entity.host, lookupField:id
| fieldsAdd tags = `lookup.tags[]`
| fieldsAdd buIndex = contains(tags[],"DEPARTMENT:")
| fieldsAdd test = arrayIndexOf(buIndex, TRUE)
| fieldsAdd BU = tags[test]
| fieldsAdd buIndex = contains(tags[],"DEPARTMENT:")

The code above checks each array element and return true if it matches the above. 

The next piece of code then the element where 'true' was found including its index.

Where I have the field BU, is to access the index stored in test to give me the DEPARTMENT: text. However, I can't seem to figure it out. Any ideas? 

4 REPLIES 4

PacoPorro
Dynatrace Leader
Dynatrace Leader

Do you know expand can be used to separate the tags? https://docs.dynatrace.com/docs/shortlink/structuring-commands#expand

How would I utilise it to grab a specific tag if its located in different array elements? 

Expand tags and filter tags containing Department  ?

krzysztof_hoja
Dynatrace Champion
Dynatrace Champion

You can use iterative expressions to interact with arrays (fields tags is array of strings):

First I parse tags into array of records containing context, tag and its value:

timeseries { percent = avg(dt.host.disk.used.percent), used = avg(dt.host.disk.used), avail = avg(dt.host.disk.avail) }, by: { dt.entity.host, dt.entity.disk }
| fieldsAdd Utilisation = arrayAvg(percent), entityName(dt.entity.disk)
| fieldsAdd entityName(dt.entity.host)
| fieldsAdd entityAttr(dt.entity.host, "tags")

| fieldsAdd ptags = parse(dt.entity.host.tags[], """('[' LD:context ']')?((LD:tag (!<<'\\' ':') LD:value)|LD:tag)""")
| fieldsAdd ptags = record(context=ptags[][context], tag=replaceString(ptags[][tag],"\\:",":"),  value=replaceString(ptags[][value],"\\:",":"))

| fieldsAdd department= arrayFirst(iCollectArray((if(ptags[][tag]=="DEPARTMENT", ptags[][value]))))

and later I can pick any element of this array using any condition based on record (I filter by tag name only in this example.

Featured Posts