2017-11-02 3 views
1

내가 redis를 처음 접했기 때문에 REDIS에서 JSON의 요소에 액세스 할 수 있도록 아래에 복잡한 json을 저장하는 방법에 대한 지침이 필요합니다. -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/호스트 이름/InstanceID를 쿼리하는 방식으로이 파일을 저장해야합니다.

위의 지침이 필요합니다.

답변

4

직접 할 수는 없지만 다행스럽게도 ReJSON이라는 새로운 Redis 모듈이 필요합니다.이 모듈은 멋진 Python 바인딩을 가지고 있습니다. Redis 4.0을 사용하고 ReJSON을 컴파일하고 설치하고 redis를로드하도록 구성해야하며 JSON 조작을위한 기본 명령을 추가해야합니다.

이 옵션을 사용하면 JSON 문서를 redis로 저장 한 다음 문서를 가져 오지 않고 (또는 내부적으로 파싱하지 않고) 문서 트리에서 특정 요소를 가져 오거나 수정할 수 있습니다. 파이썬 클라이언트는 심지어 파이썬 딕테이션을 저장하고이를 JSON으로 자동 변환합니다.

ReJSON 모듈 : http://rejson.io

파이썬 클라이언트 : 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)) 

가 레디 스에서 값을 얻으려면 : 난 경우

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 내부에서 피클 링 된 객체를 수정할 수는 없으며,로드하고 직렬화하면 속도가 느릴뿐만 아니라 데이터가 실제로 빠르게 일치합니다. –

+0

목표는 데이터를 redis에 저장하고 즉시 수정하지 않는 것입니다. 나는 당신이 그렇게하기 위해 reJson을 사용할 수 있음을 알고있었습니다. 단지 대안을주었습니다 : – Adarsh

+0

reJson은 또한 4.0 이상의 최소 redis 요구를 필요로합니다. 링크 : http://rejson.io/ – Adarsh

관련 문제