在bash中使用jq在json文档上进行链选择和max_by

Rag*_*Pwn 2 bash json jq

我想获取具有最大SnapshotCreateTime的快照的SnapshotIdentifier,并通过ClusterIdentifier对其进行过滤。这是我正在使用的命令:

aws redshift describe-cluster-snapshots --region us-west-2 |
  jq -r '.Snapshots[]
         | select(.ClusterIdentifier == "dev-cluster")
         | max_by(.SnapshotCreateTime) 
         | .SnapshotIdentifier '
Run Code Online (Sandbox Code Playgroud)

这是json

{
    "Snapshots": [        
        {
                "EstimatedSecondsToCompletion": 0, 
                "OwnerAccount": "45645641155", 
                "CurrentBackupRateInMegaBytesPerSecond": 6.2857, 
                "ActualIncrementalBackupSizeInMegaBytes": 22.0, 
                "NumberOfNodes": 3, 
                "Status": "available", 
                "VpcId": "myvpc", 
                "ClusterVersion": "1.0", 
                "Tags": [], 
                "MasterUsername": "ayxbizops", 
                "TotalBackupSizeInMegaBytes": 192959.0, 
                "DBName": "dev", 
                "BackupProgressInMegaBytes": 22.0, 
                "ClusterCreateTime": "2016-09-06T15:56:08.170Z", 
                "RestorableNodeTypes": [
                    "dc1.large"
                ], 
                "EncryptedWithHSM": false, 
                "ClusterIdentifier": "dev-cluster", 
                "SnapshotCreateTime": "2016-09-06T16:00:25.595Z", 
                "AvailabilityZone": "us-west-2c", 
                "NodeType": "dc1.large", 
                "Encrypted": false, 
                "ElapsedTimeInSeconds": 3, 
                "SnapshotType": "manual", 
                "Port": 5439, 
                "SnapshotIdentifier": "thismorning"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

pea*_*eak 5

  1. max_by需要一个数组作为输入。因此,您的过滤器的以下变体将起作用:

    [.Snapshots[] | select(.ClusterIdentifier == "dev-cluster")]
    | max_by(.SnapshotCreateTime)
    | .SnapshotIdentifier
    
    Run Code Online (Sandbox Code Playgroud)
  2. 根据您的口头描述,它似乎要运行max_by之前select

    .Snapshots
    | max_by(.SnapshotCreateTime)
    | select(.ClusterIdentifier == "dev-cluster")
    | .SnapshotIdentifier
    
    Run Code Online (Sandbox Code Playgroud)
  3. 如果最大对象可能不止一个,则可能要使用maximal_by而不是max_by

    def maximal_by(f):
      (map(f) | max) as $mx
      | .[] | select(f == $mx);
    
    Run Code Online (Sandbox Code Playgroud)