Hello,
I have the following example json data:
spec: {
field1: X,
field2: Y,
field3: Z,
containers: [
{
name: A
privileged: true
},
{
name: B
},
{
name: C
privileged: true
}
]
}
I'm trying to write a query that only returns privileged containers. I've been trying to use mvfilter but that won't return the name of the container. Here's what I was trying to do:
index=MyIndex spec.containers{}.privileged=true
| eval priv_containers=mvfilter(match('spec.containers{}.privileged',"true"))
| stats values(priv_containers) count by field1, field2, field3
This will, however, just return "true" in the priv_containers values column, instead of the container's name. What would be the best way to accomplish that?
JSON array must first be converted to multivalue before you can use mv-functions. The classic method to do this is mvexpand together with spath.
| spath input=spec path=spec.containers{}
| mvexpand spec.containers{}
| spath input=spec.containers{}
| where privileged == "true"
With your sample data, output is like
name | privileged | spec.containers{} | spec.field1 | spec.field2 | spec.field3 |
A | true | { "name": "A", "privileged": "true" } | X | Y | Z |
C | true | { "name": "C", "privileged": "true" } | X | Y | Z |
If the array is big and events are many, mvexpand risk running out of memory. So, Splunk 8 introduced a group of JSON functions. The following is more memory efficient (and likely more efficient in general), but the output is multivalued.
| spath input=spec path=spec.containers{}
| fields - spec.containers{}.*
| eval privileged_containers = mvfilter(json_extract('spec.containers{}', "privileged") == "true")
Your sample data would give something like
privileged_containers | spec.containers{} | spec.field1 | spec.field2 | spec.field3 |
{ "name": "A", "privileged": "true" } { "name": "C", "privileged": "true" } | { "name": "A", "privileged": "true" } { "name": "B" } { "name": "C", "privileged": "true" } | X | Y | Z |
BTW, please post JSON in raw text and make sure the format is compliant with proper quotes, etc. so volunteers don't have to waste time reconstruct data or worry about noncompliant data. Here is a compliant emulation that you can play with and compare with real data
| makeresults
| eval _raw = "{\"spec\": {
\"field1\": \"X\",
\"field2\": \"Y\",
\"field3\": \"Z\",
\"containers\": [
{
\"name\": \"A\",
\"privileged\": \"true\"
},
{
\"name\": \"B\"
},
{
\"name\": \"C\",
\"privileged\": \"true\"
}
]
}}"
| spath
``` data emulation above ```
Hope this helps.