Subscribed unsubscribe Subscribe Subscribe

DynamoDBからデータを取得してみる(query)

テーブル定義

  Views:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: VIEWS
      KeySchema:
        -
          AttributeName: ID
          KeyType: HASH
      GlobalSecondaryIndexes:
        -
          IndexName: GSI_URL
          KeySchema:
            -
              AttributeName: URL
              KeyType: HASH
          Projection:
            NonKeyAttributes:
              - ID
            ProjectionType: INCLUDE
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
      AttributeDefinitions:
        -
          AttributeName: ID
          AttributeType: N
        -
          AttributeName: URL
          AttributeType: S
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES

Lambdaのソース(Python2.7)

※VIEWSテーブルからURLが/のデータを取得します

from __future__ import print_function
from boto3.dynamodb.conditions import Key, Attr
import json
import boto3

dynamodb = boto3.resource('dynamodb')

print('Loading function')

def handler(event, context):
  print("Received event: " + json.dumps(event, indent=2))

  try:
    views = dynamodb.Table('VIEWS')
    response = views.query(
      IndexName='GSI_URL',
      KeyConditionExpression=Key('URL').eq('/')
    )
    print(response)
    return {'data':response}
  except Exception as e:
    print(e)
    raise(e)

取得できたデータ

カウントも同時に返してくれるのは便利ですね。

{
  "data": {
    "Count": 4,
    "Items": [
      {
        "URL": "/",
        "ID": 3
      },
      {
        "URL": "/",
        "ID": 2
      },
      {
        "URL": "/",
        "ID": 1
      },
      {
        "URL": "/",
        "ID": 5
      }
    ],
    "ScannedCount": 4,
    "ResponseMetadata": {
      "RetryAttempts": 0,
      "HTTPStatusCode": 200,
      "RequestId": "XXXXXXXXXXXXXXXXXXXXXX",
      "HTTPHeaders": {
        "x-amzn-requestid": "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "content-length": "170",
        "server": "Server",
        "connection": "keep-alive",
        "x-amz-crc32": "1111111111111111",
        "date": "Mon, 10 Oct 2016 10:22:48 GMT",
        "content-type": "application/x-amz-json-1.0"
      }
    }
  }
}