mightyMouse
mightyMouse

Reputation: 738

Query DynamoDB using a script in AWS

I have a DynamoDB table. I need to perform write/read/delete operations on this table. This needs to be done using a script. I can think of two approaches:

  1. Using AWS Lambda
  2. Using AWS Cloud9

Are there any other ways to do this task using the services provided by AWS?

Upvotes: 0

Views: 1522

Answers (2)

Jon
Jon

Reputation: 31

My answer is a quick solution for development purposes and not conducive to a thorough strategy or proper architecture.

If you are working in a cloud9 environment and want to quickly query dynamodb from within that environment, you may find it useful to create a python script which you can then quickly and easily run. This will save you having to deploy / configure additional infrastructure.

Python Code:

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb', region_name='ab-cont-1')
table = dynamodb.Table('MyTableName')

response = table.query(
    ProjectionExpression="Col1, Col2",
    KeyConditionExpression=Key('Col1').eq(123)
)

print(response['Items'])

If this is saved as script.py in the current working directory, from the shell:

#pip3 install boto3
python3 script.py 

Upvotes: 0

Daniel_Pickens
Daniel_Pickens

Reputation: 54

For using AWS Lambda , there is a method to integrate your DynamoDB table with a AWS Lambda function. First, you need to:

1.Create a new Lambda function and DynamoDB database that are integrated together

The first thing you will need to do if you have already created the DynamoDB table:

create the function:

amplify add function

? Provide a friendly name for your resource to be used as a label for this category in the project: mylambda
? Provide the AWS Lambda function name: mylambda
? Choose the function runtime that you want to use: NodeJS
? Choose the function template that you want to use: Hello World
? Do you want to access other resources created in this project from your Lambda function? Y
? Select the category: storage
? Select the operations you want to permit for testtable: create, read, update, delete
? Do you want to invoke this function on a recurring schedule? N
? Do you want to edit the local lambda function now? N

Deploy the function and database:

amplify push

  1. Next you can call DynamoDB table from Lambda in Node.js by:

A.) Create an item in DynamoDB from Lambda

To create an item in DynamoDB you can use the put method:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : 'your-table-name',
  /* Item properties will depend on your application concerns */
  Item: {
     id: '12345',
     price: 100.00
  }
}

async function createItem(){
  try {
    await docClient.put(params).promise();
  } catch (err) {
    return err;
  }
}

exports.handler = async (event) => {
  try {
    await createItem()
    return { body: 'Successfully created item!' }
  } catch (err) {
    return { error: err }
  }
};

Getting an item by primary key in DynamoDB from Lambda: You can also obtain a primary key from DynamoDB by using the get method. A get request returns a single item given the primary key of that item:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : 'your-table-name',
  /* Item properties will depend on your application concerns */
  Key: {
    id: '12345'
  }
}

async function getItem(){
  try {
    const data = await docClient.get(params).promise()
    return data
  } catch (err) {
    return err
  }
}

exports.handler = async (event, context) => {
  try {
    const data = await getItem()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

Scanning a table: This will return one or more items and item attributes by accessing every item in a table or a secondary index.

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : 'your-table-name'
}

async function listItems(){
  try {
    const data = await docClient.scan(params).promise()
    return data
  } catch (err) {
    return err
  }
}

exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}


Querying a table: A query returns one or more items and item attributes by querying items from a table by primary key or secondary index.

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

var params = {
  TableName: 'your-table-name',
  IndexName: 'some-index',
  KeyConditionExpression: '#name = :value',
  ExpressionAttributeValues: { ':value': 'shoes' },
  ExpressionAttributeNames: { '#name': 'name' }
}

async function queryItems(){
  try {
    const data = await docClient.query(params).promise()
    return data
  } catch (err) {
    return err
  }
}

exports.handler = async (event, context) => {
  try {
    const data = await queryItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

Upvotes: 1

Related Questions