Amazon DynamoDB 用 NoSQL Workbench が GA されました

記事タイトルとURLをコピーする

はじめに

こんにちは、技術一課の山中です。 春ですね、春です。

NoSQL Workbench とは

NoSQL Workbench は AWS から提供されている DynamoDB のためのツールで、macOS 及び Windows で利用可能です。 先日までプレビュー版として提供されていましたが、先日 GA されました!!

https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/workbench.html

このツールでデータの可視化や追加、更新等ができる他、データモデリングやクエリ開発等が行えます。 本ブログではデータモデリング部分をご紹介したかったのですが、内容が重くなってきたので、インストールしてクエリを発行するところまでやってみたいと思います。

事前準備

ダウンロード

まずは、 NoSQL Workbench をダウンロードします。 macOS と Windows 用のリンクがあるので、注意してください。 今回は macOS 版をダウンロードしました。

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workbench.settingup.html

試してみる

NoSQL Workbench を開き早速使ってみましょう!

アプリケーションを開くと以下のような画面がでてきます。 デフォルトで、 AWS が提供するサンプルデータが用意されているようです。

バージョンを確認すると、 1.0.0 となっていました。

今回はお試しなので、 Operation builder を開いてみます。 開くと、ローカル PC で設定している AWS のクレデンシャル情報がでてきました。

~/.aws/config の情報を持ってきているようです。 利用したいクレデンシャルカードで Open をクリックすると、その権限で参照可能な DynamoDB テーブルを表示してくれます。

試しに、一つテーブルを選択してみましょう。 テーブル名を選択すると、格納されているアイテムが表示されました。

右上の Build operations から Query を選びます。

Partition key や Sort key の範囲指定などプライマリーキーに対する条件指定や、各種細かい指定ができます。 Execute を選択するとクエリが実行されます。

また、 Generate code を選択するとクエリのコードが生成されます。 これは便利!

以下は生成された Python のコードです。


# Before running the code below, please follow these steps to setup your workspace if you have not
# set it up already:
#
# 1. Setup credentials for DynamoDB access. One of the ways to setup credentials is to add them to
#    ~/.aws/credentials file (C:\Users\USER_NAME\.aws\credentials file for Windows users) in
#    following format:
#
#    []
#    aws_access_key_id = YOUR_ACCESS_KEY_ID
#    aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
#
#    If  is specified as "default" then AWS SDKs and CLI will be able to read the credentials
#    without any additional configuration. But if a different profile name is used then it needs to be
#    specified while initializing DynamoDB client via AWS SDKs or while configuring AWS CLI.
#    Please refer following guide for more details on credential configuration:
#    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration
#
# 2. Install the latest Boto 3 release via pip:
#
#    pip install boto3
#
#    Please refer following guide for more details on Boto 3 installation:
#    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#installation
#    Please note that you may need to follow additional setup steps for using Boto 3 from an IDE. Refer
#    your IDE's documentation if you run into issues.


# Load the AWS SDK for Python
import boto3
from botocore.exceptions import ClientError

ERROR_HELP_STRINGS = {
    # Common Errors
    'InternalServerError': 'Internal Server Error, generally safe to retry with exponential back-off',
    'ProvisionedThroughputExceededException': 'Request rate is too high. If you\'re using a custom retry strategy make sure to retry with exponential back-off.' +
                                              'Otherwise consider reducing frequency of requests or increasing provisioned capacity for your table or secondary index',
    'ResourceNotFoundException': 'One of the tables was not found, verify table exists before retrying',
    'ServiceUnavailable': 'Had trouble reaching DynamoDB. generally safe to retry with exponential back-off',
    'ThrottlingException': 'Request denied due to throttling, generally safe to retry with exponential back-off',
    'UnrecognizedClientException': 'The request signature is incorrect most likely due to an invalid AWS access key ID or secret key, fix before retrying',
    'ValidationException': 'The input fails to satisfy the constraints specified by DynamoDB, fix input before retrying',
    'RequestLimitExceeded': 'Throughput exceeds the current throughput limit for your account, increase account level throughput before retrying',
}

# Use the following function instead when using DynamoDB Local
#def create_dynamodb_client(region):
#    return boto3.client("dynamodb", region_name="localhost", endpoint_url="http://localhost:8000", aws_access_key_id="access_key_id", aws_secret_access_key="secret_access_key")

def create_dynamodb_client(region="us-east-1"):
    return boto3.client("dynamodb", region_name=region)


def create_query_input():
    return {
        "TableName": "CustomerAndOrders",
        "KeyConditionExpression": "#b3f70 = :b3f70",
        "FilterExpression": "#b3f71 = :b3f71",
        "ExpressionAttributeNames": {"#b3f70":"customerId","#b3f71":"deliveryAddress"},
        "ExpressionAttributeValues": {":b3f70": {"S":"123"},":b3f71": {"S":"there"}}
    }


def execute_query(dynamodb_client, input):
    try:
        response = dynamodb_client.query(**input)
        print("Query successful.")
        # Handle response
    except ClientError as error:
        handle_error(error)
    except BaseException as error:
        print("Unknown error while querying: " + error.response['Error']['Message'])


def handle_error(error):
    error_code = error.response['Error']['Code']
    error_message = error.response['Error']['Message']

    error_help_string = ERROR_HELP_STRINGS[error_code]

    print('[{error_code}] {help_string}. Error message: {error_message}'
          .format(error_code=error_code,
                  help_string=error_help_string,
                  error_message=error_message))


def main():
    # Create the DynamoDB Client with the region you want
    dynamodb_client = create_dynamodb_client(region="eu-west-1")

    # Create the dictionary containing arguments for query call
    query_input = create_query_input()

    # Call DynamoDB's query API
    execute_query(dynamodb_client, query_input)


if __name__ == "__main__":
    main()

おわりに

いかがだったでしょうか? 今回は少しだけ触ってみたのですが、結構簡単に使うことができました。 今度はデータモデリング等をこれでやってみたいとおもいます!

また、本ブログの内容は 2020/3/11 (水) 12:00 より YouTube Live で配信される「30分でわかる AWS UPDATE!」でも取り上げる予定ですので、ぜひご覧ください!

https://youtu.be/5gMsg1r0Z9E

参考