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
Related
I'm including facial recognition in my Electron app using Node.js and I would like to know if I'm doing the process correctly, as I was a little confused by some points in the documentation.
I'm using the aws-sdk library and I want that, when taking a picture of the user, my system searches for him in the database of faces registered in Rekognition and returns me who this user is - that is, his userId in my MySQL database.
I've already created a Collection called "Users" and I would like to know how to inform the userId to the indexFaces method. Initially, I intend to allow the inclusion of only one photo per user and I'm currently doing it like this:
const params = {
CollectionId: 'Users',
Image: { Bytes }, // The image in base64
ExternalImageId: '1', // The userId in MySQL
MaxFaces: 1,
QualityFilter: 'HIGH'
};
Rekognition.indexFaces(params, (err, data) => {
if (err) {
console.log(err, err.stack);
return;
}
console.log(data);
});
The entire face registration process works normally and the code I use to search for the faces already registered is:
const params = {
CollectionId: 'Users',
Image: { Bytes }, // The image in base64
MaxFaces: 1,
FaceMatchThreshold: 99
};
Rekognition.searchFacesByImage(params, (err, data) => {
if (err) {
console.log(err, err.stack);
return;
}
for (let i = 0; i < data.FaceMatches.length; i++) {
console.log(data.FaceMatches[i].Face);
}
});
If the consulted face is registered and found in the Collection, the value returned is:
{
FaceId: 'b7506fc1-e8...',
BoundingBox: {...},
ImageId: 'e11d94c1-831...',
ExternalImageId: '1', // `userId` in my MySQL as desired
Confidence: 99.999...,
IndexFacesModelVersion: '6.0'
}
My question is: am I associating the userId with the face correctly through the ExternalImageId property or should I do it in a more appropriate way? If yes, how?
Yes, that is the purpose of the ExternalImageId field -- it is for you to associate your own reference to the face. You are doing it correctly (assuming that the code works).
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 want to create a new user in dynamodb but before that I want to check that user is present in db or not. Here Primary partition key is username. I Want to check both emailId and username in the condition. Both should be unique. For example
user1 user1#gmail.com
user2 user2#gmail.com
user3 user3#gmail.com
Example1 When I create a new user username= user4 and emailId=user1#gmail.com It should not create a new user because emailId is already present.
Example2 When I create a new user username= user1 and emailId=user4#gmail.com It should not create a new user because username is already present.
So these are the scenarios. Can anybody tell what is the best solution for this?
I found the solution using scan method
const AWS = require('aws-sdk');
const dynamoDb_DocumentClient = new AWS.DynamoDB.DocumentClient();
let params = {
TableName: "OP-User",
ProjectionExpression: 'userName, emailAddress',
FilterExpression: "userName = :userName OR emailAddress = :emailAddress",
ExpressionAttributeValues: {
":userName": "user1",
":emailAddress": "user111#asurion.com"
}
};
dynamoDb_DocumentClient.scan(params, function (err, data) {
if (err) {
console.log("err: " + err);
}
console.log("data: " + data);
});
Can we have another solution for this ? using Query, Indexname? like this.
Any suggestion would be appreciated.
Thanks,
Use AWS DynamoDB Conditional Expressions to compare Username and ID attributes, before creating and item.
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 + ")");
});
}
});
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