I am quite new to work with DynamoDB. I would like to query DynamoDB database for a specific column value and get the data that matches that specific column value using NodeJS sdk
In this case, the DynamoDB is already deployed.
Please suggest how to implement this workflow using Node JS.
most important thing is to create a JSON object containing
the parameters needed to query the table, which in this example includes the table name, the
ExpressionAttributeValues needed by the query, a KeyConditionExpression that uses those
values to define which items the query returns, and the names of attribute values to return for each
item. Call the query method of the DynamoDB service object.
here is an example to query dynamodb with nodejs sdk
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
ExpressionAttributeValues: {
':s': {N: '2'},
':e' : {N: '09'},
':topic' : {S: 'PHRASE'}
},
KeyConditionExpression: 'Season = :s and Episode > :e',
ProjectionExpression: 'Episode, Title, Subtitle',
FilterExpression: 'contains (Subtitle, :topic)',
TableName: 'EPISODES_TABLE'
};
b.query(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
data.Items.forEach(function(element, index, array) {
console.log(element.Title.S + " (" + element.Subtitle.S + ")");
});
}
});
Related
I am trying to retrieve values from DynamoDB when passing the primary partition key as the parameters in the URL.
I have a table with two columns:
movie id
movie name.
I want to be able to pass the movie id in the URL and to get the correspondent movie as a result. I have already created following lambda function and connected it to an API and DynamoDB.
I am not able to figure out the piece of code to use in order to retrieve the movie name when passing movie id as a parameter
Here is my code so far:
console.log('Loading function');
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});
exports.handler = function(event, context,callback) {
var params = {
TableName: 'movie',
Key: {
"movieID": 5,
}
}
docClient.get(params, function(err, data){
if(err){
callback(err,null);
}else{
callback(null, data);
}
})
};
Try
var params = {
TableName: 'movie',
Key: {
"movieID": 5,
},
AttributesToGet= [
"movie_name"
],
ProjectionExpression: 'movie_name"
}
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html
AttributesToGet is a legacy field as per documentation and ProjectionExpression should be used instead.
I am trying to create a silent auction site. My Lambda function should update an item under the condition that the submitted bid > current high bid. However, the condition does not seem to be applying; the update occurs even if the submitted bid is less than the current high bid.
Please help me identify what I'm doing wrong:
##My DynamoDB table looks like this:##
Table name: SilentAuction2
Primary partition key: ItemID (String)
other attributes:
CurrentHighBid (Number)
HighestBidder (String)
Notes (String)
BidHistoryBids (List)
BidHistoryPPL (List)
My condition, as stated above, is that the incoming event.NewBid is greater than the CurrentHighBid. Here is the Lambda code in Node.JS:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = function index(event, context, callback) {
var table = "SilentAuction2";
var ItemID = event.ItemID;
var NewBid = event.NewBid;
var NewBidder = event.NewBidder;
var Notes = event.Notes;
var params = {
TableName:table,
Key:{
"ItemID": ItemID
},
//update and append values
UpdateExpression: "SET #BidList = list_append(#BidList, :hb),
#PplList = list_append(#PplList, :hp),
CurrentHighBid =:c,
HighestBidder=:h,
Notes=:n",
//condition on which to update if true
ConditionalExpression: " :c > CurrentHighBid",
ExpressionAttributeNames: {
"#BidList" : "BidHistoryBids",
"#PplList" : "BidHistoryPPL"
},
ExpressionAttributeValues:{
":hb":[NewBid],
":hp":[NewBidder],
":n":Notes,
":c":NewBid,
":h":NewBidder
},
ReturnValues:"UPDATED_NEW"
};
docClient.update(params, function(err, data){
if(err){
callback(err, null);
}else{
callback(null, data);
}
});
};
This links were helpful in researching ConditionalExpression within DynamoDB:
https://egkatzioura.com/2016/08/09/update-dynamodb-items-with-node-js/
http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.05
i am working on node js using dynamoDB with dynamoose. For example, let us assume we have a table Employees in which there is two attributes Branch and Domain. I have a given branch and domain, now i want to get all the employees under either the given branch or the give domain. Can anyone please give an example for above case?
Here is the code to query and scan.
The code connects to DynamoDB local instance.
Employee Schema used:-
Branch - Hash Key
No sort key in the table
Domain - is the attribute
Code:-
var dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
accessKeyId : 'AKID',
secretAccessKey : 'SECRET',
region : 'us-east-1'
});
dynamoose.local();
var Schema = dynamoose.Schema;
var Table = dynamoose.Table;
var Employee = dynamoose.model('employee', { branch: String, domain: String });
Employee.get('UK').then(function (data) {
console.log('Get :' + JSON.stringify(data));
});
Employee.query('branch').eq('UK').exec(function (err, data) {
console.log('Query :' + JSON.stringify(data));
});
Employee.scan('domain').eq('Banking').exec(function (err, data) {
console.log('Scan :' + JSON.stringify(data));
});
Explanation:-
Employee.get(..) - Get the data by hash key
Employee.query (..) - Get the data by hash key along with other attributes as needed
Employee.scan (..) - Get the data based on non-key attributes
How do you count as like mysql "select count(*) from tablename" , in DynamoDB using the dynamoose node module?
There is no direct equivalent available in DynamoDB. However, one workaround would be to get the ItemCount using describe table API.
Drawback of ItemCount:-
DynamoDB updates this value approximately every six hours. Recent
changes might not be reflected in this value.
Code to get item count of Movies table from local DynamoDB instance:-
'use strict';
var dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
accessKeyId : 'AKID',
secretAccessKey : 'SECRET',
region : 'us-east-1'
});
dynamoose.local();
var Schema = dynamoose.Schema;
var Table = dynamoose.Table;
var table = new Table('Movies', null, null, dynamoose);
table.describe(function(err, data) {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data, null, 2));
console.log("Number of item =====>", JSON.stringify(data.Table.ItemCount, null, 2));
}
});
Output:-
Number of item =====> 24
I am using the AWS.DynamoDB.DocumentClient, with Dynamodb local (port 8080). When I perform a put, the data variable in the callback is an empty object. Have I missed something?
import * as AWS from "aws-sdk";
AWS.config.update({
region: "us-west-2",
endpoint: "http://localhost:8080"
});
const docClient: any = new AWS.DynamoDB.DocumentClient();
const item = {
someField: "456",
other: "123"
};
const params = {
TableName: "TableName",
Item: item
};
docClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data); // this produces: {}
});
There is no error, and the item is being inserted\updated - however the data variable is an empty object. Shouldn't this contain values?
Thanks
You aren't asking for any values to come back, so why do you expect there to be any values coming back? You'll need to set the appropriate parameters ReturnConsumedCapacity and/or ReturnItemCollectionMetrics and/or ReturnValues if you are wanting any of that to come back in the response.
As you can't set a value for "ReturnValues" that actually returns anything useful, I worked around it by simple passing back the original item data that was passed in.
import * as AWS from "aws-sdk";
AWS.config.update({
region: "us-west-2",
endpoint: "http://localhost:8080"
});
const docClient: any = new AWS.DynamoDB.DocumentClient();
const item = {
someField: "456",
other: "123"
};
const params = {
TableName: "TableName",
Item: item
};
// Have a clear reference to this scope
var self = this;
docClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(self.params.Item); // this should return the data you passed in!
});
I set "self" as "this" to make it clear where I'm reading the data from. Hope that helps someone!
To clarify accepted answer a bit.
Set the return value as:
var params = {
Item: data,
TableName: 'myTable',
ReturnValues: 'ALL_OLD'
}
The docs specify:
NONE - If ReturnValues is not specified, or if its value is NONE, then nothing is returned. (This setting is the default for ReturnValues.)
ALL_OLD - If PutItem overwrote an attribute name-value pair, then the content of the old item is returned.
Note: The ReturnValues parameter is used by several DynamoDB operations; however, PutItem does not recognize any values other than NONE or ALL_OLD.
This effectively means as the answer by Walter White describes that unless there is an update to an existing item that nothing will be returned.