Kurt Peek
Kurt Peek

Reputation: 57741

How to determine the length of an array field in Splunk?

I've imported the following data (located on my local machine in the $SPLUNK_DATA directory) to Splunk:

{"level":"info","msg":"","restaurants":[{"name":"El Farolito","cuisine":"Mexican"}],"time":"2024-09-29T12:32:37-07:00"}
{"level":"info","msg":"","restaurants":[{"name":"Flour + Water","cuisine":"Italian"},{"name":"San Ho Won","cuisine":"Korean"}],"time":"2024-09-29T12:32:37-07:00"}

I'm trying to sort the data by the number of restaurants in each log entry. After starting Splunk using Docker with the command

docker run -it -e SPLUNK_START_ARGS=--accept-license -e SPLUNK_PASSWORD=helloworld -p 8000:8000 -p 8089:8089 --volume $SPLUNK_DATA:/home/splunk splunk/splunk start

I navigated to localhost:8000, logged in with username admin and password helloworld, and went to Settings -> Data input -> File and imported that file from /home/splunk:

enter image description here

Now I'd like to add a new field n which represents the number of restaurants. Using a previous StackOverflow answer I received, How to evaluate a Splunk field which represents the length of another field?, I tried

index=main | eval n=mvcount('restaurants{}')

However, that doesn't seem to work: as seen from the table view below, n is empty:

enter image description here

How can I make it such that n is 2 for the first log entry and 1 for the second one (i.e., the number of restaurants)?

Upvotes: 0

Views: 607

Answers (1)

DuesserBaest
DuesserBaest

Reputation: 2829

Try this run-anywhere-SPL:

| makeresults ```start mock data```
    format=json 
    data="
        [
         {\"level\":\"info\",\"msg\":\"\",\"restaurants\":[{\"name\":\"El Farolito\",\"cuisine\":\"Mexican\"}],\"time\":\"2024-09-29T12:32:37-07:00\"},
         {\"level\":\"info\",\"msg\":\"\",\"restaurants\":[{\"name\":\"Flour + Water\",\"cuisine\":\"Italian\"},{\"name\":\"San Ho Won\",\"cuisine\":\"Korean\"}],\"time\":\"2024-09-29T12:32:37-07:00\"}
        ]
    "
| spath 
```end mock data```
| eval n=mvcount('restaurants{}.name')
| fields "restaurants{}.name" n
| table "restaurants{}.name" n

The issue is that a) there is no field restaurants{} on which you could do an mvcount(). You can however access restaurants{}.name or restaurants{}.cuisine to get the count which each possess a multivalue field thats countable.

Upvotes: 3

Related Questions