DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Fixing Common Oracle Database Problems
  • How to Restore a Transaction Log Backup in SQL Server
  • Why I Built the Ultimate Text Comparison Tool (And Why You Should Try It)
  • Enhancing Avro With Semantic Metadata Using Logical Types

Trending

  • Java Virtual Threads and Scaling
  • Understanding Java Signals
  • Develop a Reverse Proxy With Caching in Go
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  1. DZone
  2. Data Engineering
  3. Databases
  4. Query DynamoDB Items With Node.js

Query DynamoDB Items With Node.js

We have a look at querying data in DynamoDB using Node.js along with some example code.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Jul. 07, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
68.0K Views

Join the DZone community and get the full member experience.

Join For Free

In a previous post, we tackled inserting data into a DynamoDB database.

In this tutorial, we will issue some basic queries against our DynamoDB tables.

The main rule is that every query has to use the hash key.

The simplest form of query is using the hash key only. We will query the Users table on this one. There would be only one result, therefore there is no use iterating the Items list.

var getUser = function(email,callback) {

    var docClient = new AWS.DynamoDB.DocumentClient();

    var params = {
        TableName: "Users",
        KeyConditionExpression: "#email = :email",
        ExpressionAttributeNames:{
            "#email": "email"
            },
        ExpressionAttributeValues: {
            ":email":email
            }
        };

    docClient.query(params,callback);
    };


However, we can issue more complex queries using conditions. The Logins Table works well for an example. We will issue a query that will fetch login attempts between to dates.

var queryLogins = function(email,from,to,callback) {

    var docClient = new AWS.DynamoDB.DocumentClient();

    var params = {
        TableName:"Logins",
        KeyConditionExpression:"#email = :emailValue and #timestamp BETWEEN :from AND :to",
        ExpressionAttributeNames: {
            "#email":"email",
            "#timestamp":"timestamp"
            },
        ExpressionAttributeValues: {
            ":emailValue":email,
            ":from": from.getTime(),
            ":to":to.getTime()
            }
        };

    var items = []

    var queryExecute = function(callback) {

        docClient.query(params,function(err,result) {

            if(err) {
                callback(err);
                } else {

                console.log(result)

                items = items.concat(result.Items);

                if(result.LastEvaluatedKey) {

                    params.ExclusiveStartKey = result.LastEvaluatedKey;
                    queryExecute(callback);
                    } else {
                        callback(err,items);
                    }
                }
            });
        }

        queryExecute(callback);
    };

Keep in mind that DynamoDB fetches data in pages, therefore you have to issue the same request more than once in the case of multiple pages. You have to use the last evaluated key to your next request. If there are a lot of entries, be aware that you should handle the call stack size.

Last but not least, querying on indexes is one of the basic actions. It is the same routine either for local or global secondary indexes. Keep in mind that the results fetched depend on the projection type we specified once creating the Table. In our case, the projection type is for all fields.

We shall use the Supervisors table.

var docClient = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName: "Supervisors",
    IndexName: "FactoryIndex",
    KeyConditionExpression:"#company = :companyValue and #factory = :factoryValue",
    ExpressionAttributeNames: {
        "#company":"company",
        "#factory":"factory"
        },
    ExpressionAttributeValues: {
        ":companyValue": company,
        ":factoryValue": factory
        }
    };

docClient.query(params,callback);


You can find full source code with unit tests on GitHub.

Related Refcard:

Node.js

Database

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Fixing Common Oracle Database Problems
  • How to Restore a Transaction Log Backup in SQL Server
  • Why I Built the Ultimate Text Comparison Tool (And Why You Should Try It)
  • Enhancing Avro With Semantic Metadata Using Logical Types

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!