2017-11-02 1 views
1

私はRedisには新しいので、REDISからJSONの要素にアクセスできるように、以下の複雑なjsonをREDISに格納する方法についていくつかのガイダンスが必要です -Pythonを使ってRedisに複雑な入れ子になったJSONを格納する方法

"Reservations": [ 
     { 
      "Instances": [ 
       { 
        "Monitoring": { 
         "State": "disabled" 
        }, 
        "PublicDnsName": "", 
        "State": { 
         "Code": 16, 
         "Name": "running" 
        }, 
        "EbsOptimized": "false", 
        "LaunchTime": "xxxxxxxxx", 
        "PrivateIpAddress": "x.x.x.x", 
        "ProductCodes": [], 
        "VpcId": "xxxxx", 
        "StateTransitionReason": "", 
        "InstanceId": "i-xxxxxxx", 
        "EnaSupport": "true", 
        "ImageId": "ami-xxxxx", 
        "PrivateDnsName": "ip-xxxxxx.ec2.internal", 
        "KeyName": "xxxxxxv", 
        "SecurityGroups": [ 
         { 
          "GroupName": "xxx", 
          "GroupId": "sg-xxxx" 
         }, 
         { 
          "GroupName": "xxxxxx", 
          "GroupId": "sg-xxxxx" 
         }, 
         { 
          "GroupName": "xxxxx", 
          "GroupId": "sg-xxxxxx" 
         }, 
         { 
          "GroupName": "xxxxx", 
          "GroupId": "sg-xxxxxx" 
         } 
        ], 
        "ClientToken": "xxxxx", 
        "SubnetId": "subnet-xxxxx", 
        "InstanceType": "t2.micro", 
        "NetworkInterfaces": [ 
         { 
          "Status": "in-use", 
          "MacAddress": "xxxxxxxx", 
          "SourceDestCheck": "true", 
          "VpcId": "vpc-xxxxx", 
          "Description": "", 
          "NetworkInterfaceId": "eni-xxxxx", 
          "PrivateIpAddresses": [ 
           { 
            "PrivateDnsName": "ip-xx-ec2.internal", 
            "Primary": "true", 
            "PrivateIpAddress": "xxxxx" 
           } 
          ], 
          "PrivateDnsName": "ip-xxxx-xx.ec2.internal", 
          "Attachment": { 
           "Status": "attached", 
           "DeviceIndex": 0, 
           "DeleteOnTermination": "true", 
           "AttachmentId": "eni-attach-xxxxx", 
           "AttachTime": "2017-0xxxxx" 
          }, 
          "Groups": [ 
           { 
            "GroupName": "xx", 
            "GroupId": "sg-xxxx" 
           }, 
           { 
            "GroupName": "xxxx", 
            "GroupId": "sg-xxx" 
           }, 
           { 
            "GroupName": "xxxx", 
            "GroupId": "sg-xxx" 
           }, 
           { 
            "GroupName": "xxxx", 
            "GroupId": "sg-xxxx" 
           } 
          ], 
          "Ipv6Addresses": [], 
          "OwnerId": "xxx", 
          "SubnetId": "subnet-xxxx", 
          "PrivateIpAddress": "1xxxx" 
         } 
        ], 
        "SourceDestCheck": "true", 
        "Placement": { 
         "Tenancy": "default", 
         "GroupName": "", 
         "AvailabilityZone": "us-xxxxxxx" 
        }, 
        "Hypervisor": "xen", 
        "BlockDeviceMappings": [ 
         { 
          "DeviceName": "/dev/xxxxxx", 
          "Ebs": { 
           "Status": "attached", 
           "DeleteOnTermination": "true", 
           "VolumeId": "vol-xxxxxx", 
           "AttachTime": "2017-xxxxxxx" 
          } 
         } 
        ], 
        "Architecture": "x86_64", 
        "RootDeviceType": "ebs", 
        "IamInstanceProfile": { 
         "Id": "xxxxxxxx", 
         "Arn": "arn:aws:iam::xxxxxxx" 
        }, 
        "RootDeviceName": "/dev/xxxxx", 
        "VirtualizationType": "hvm", 
        "Tags": [ 
         { 
          "Value": "xxxxxx", 
          "Key": "aws:cloudformation:stack-name" 
         }, 
         { 
          "Value": "xxxxxxx", 
          "Key": "aws:cloudformation:logical-id" 
         }, 
         { 
          "Value": "arn:aws:cloudformation:xxxxxx", 
          "Key": "aws:cloudformation:stack-id" 
         } 
        ], 
        "AmiLaunchIndex": 0 
       } 
      ], 
      "ReservationId": "r-xxxxx", 
      "RequesterId": "xxxxx", 
      "Groups": [], 
      "OwnerId": "xxxxxx" 
     } 
    ] 
} 

JSONに存在するすべての要素を取得するために、IP/Hostname/InstanceIDを照会する方法でこれを保存する必要があります。

私は上記のいくつかのガイダンスが必要です。

答えて

4

あなたはそれを直接行うことはできませんが、幸運なことに、ReJSONと呼ばれる新しいRedisモジュールがあります。これはあなたが必要とするものを正確に実行し、素晴らしいPythonバインディングも備えています。 Redis 4.0を使用し、ReJSONをコンパイルしてインストールし、それをロードするようにredisを設定し、JSON操作用のネイティブコマンドを追加する必要があります。

これにより、JSONドキュメントをレディスで保存し、ドキュメントを取得(または内部的に解析)することなくドキュメントツリー内の特定の要素をフェッチまたは変更することができます。 Pythonクライアントでは、Python Dictを保存して自動的にJSONに変換することもできます。

ReJSONモジュール:http://rejson.io

Pythonクライアント:https://pypi.python.org/pypi/rejson

例:あなたはreJsonを使用したくない包み

from rejson import Client, Path 

rj = Client(host='localhost', port=6379) 

# Set the key `obj` to some object 
obj = { 
    'answer': 42, 
    'arr': [None, True, 3.14], 
    'truth': { 
     'coord': 'out there' 
    } 
} 
rj.jsonset('obj', Path.rootPath(), obj) 

# Get something 
print 'Is there anybody... {}?'.format(
    rj.jsonget('obj', Path('.truth.coord')) 
) 
+0

は私の口から言葉を取った:)私場合 –

+0

作品は美しく、私は、しかし疑問を持っていますJSONのタグ要素を出力したいのですが、これをどうやってやったのですか?以下に試しましたが、エラーが表示されます - 'print(r.jsonget( 'obj'、Path( '。Reservations.Instances.Tags')) ) ' –

+0

@RohitSarkar ReJSONとは無関係ですが、あなたの道は間違っていると思います。ドキュメントを見ると、 '.Reservations [0] .Instances [0] .Tags' –

2

あなたは漬物モジュールを使用することができます。

def store_dict_data_in_redis(redis_client, key, data, ex=0): 
''' 
store dict data in redis by pickle dumps 
:param redis_client: redis client used to connect to obtain key value 
:param key: key name 
:param data: dict value 
:param ex: expiry 
:return: None 
''' 
    if ex > 0: 
     redis_client.set(key, pickle.dumps(data), ex=ex) 
    else: 
     redis_client.set(key, pickle.dumps(data)) 

のRedisから値を取得するには:Redisの中のデータを設定するには

def get_dict_data_from_redis(redis_client, key): 
''' 
obtain dict data from redis 
:param redis_client: redis client used to connect to obtain key value 
:param key: key name 
:return: dict data stored in redis 
''' 
    data = redis_client.get(key) 
    if data: 
     try: 
      return pickle.loads(data) 
     except: 
      return eval(data.decode()) 
    return {} 
+0

redisの中でpickleされたオブジェクトを変更することはできません。ロードしてシリアライズすれば、遅くなるだけでなく、データが本当に速く矛盾します。 –

+0

ここでの目標は、データを赤字で保存し、その場で変更しないことでした。私はあなたがそうするためにreJsonを使うことができると知っていました。ちょうど代替案を与えました:) – Adarsh

+0

reJsonも4.0以上の最小限のredis要件を必要とします。 リンク:http://rejson.io/ – Adarsh

関連する問題