17

I've this ElasticSearch snapshot output and would like to reduce it to print, on a single line, from each snapshot the values of the end_time_in_millis and snapshot property separate by a space:

1429609790767 snapshot_1
1429681169896 snapshot_2

Basically the output of

  • cat data | jq '.snapshots[].end_time_in_millis' and
  • cat data | jq '.snapshots[].snapshot'

but combined on one line.

I was looking at map but couldn't make out how to apply it; also reading this answer I tried:

cat data  | jq '.snapshots[] | map(. |= with_entries( select( .key == ( "snapshot") ) ) )'

But that produces lots of errors and null output.

The data:

{
  "snapshots": [
    {
      "shards": {
        "successful": 1,
        "failed": 0,
        "total": 1
      },
      "failures": [],
      "snapshot": "snapshot_1",
      "indices": [
        "myindex1"
      ],
      "state": "SUCCESS",
      "start_time": "2015-04-21T09:45:47.041Z",
      "start_time_in_millis": 1429609547041,
      "end_time": "2015-04-21T09:49:50.767Z",
      "end_time_in_millis": 1429609790767,
      "duration_in_millis": 243726
    },
    {
      "shards": {
        "successful": 1,
        "failed": 0,
        "total": 1
      },
      "failures": [],
      "snapshot": "snapshot_2",
      "indices": [
        "myindex1"
      ],
      "state": "SUCCESS",
      "start_time": "2015-04-22T05:36:02.333Z",
      "start_time_in_millis": 1429680962333,
      "end_time": "2015-04-22T05:39:29.896Z",
      "end_time_in_millis": 1429681169896,
      "duration_in_millis": 207563
    }
  ]
}
Community
  • 1
  • 1
mark
  • 6,308
  • 8
  • 46
  • 57

1 Answers1

18

Use this filter:

.snapshots[] | "\(.end_time_in_millis) \(.snapshot)"

This builds up a string for each of the snapshots consisting of the end time and the snapshot name.

Just make sure you use the -r option to get the raw output.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Perfect and thanks for the quick answer. I didn't notice http://stedolan.github.io/jq/manual/#Stringinterpolationfoo somehow – mark May 01 '15 at 08:35
  • Yep, that helped me, thank you. I needed a way to extract values from streamed JSON-L (one JSON object per line) and format them in a way that a legacy `awk`-using script could consume. – dimitarvp Mar 18 '22 at 22:52