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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Should Developers Switch From SQLite to DuckDB?
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Catching Query Regressions Before Your Users Do

Trending

  • The SDLC After AI
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Build a Voice Assistant With Gemini Live API
  • How an AI Software Factory Works: From Developer Intent to Production

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Query DynamoDB Items With Java

Query DynamoDB Items With Java

We have a look at querying items in DynamoDB with Java with some example code.

By 
Emmanouil Gkatziouras
DZone Core CORE ·
Jul. 06, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
52.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In a previous post, we proceeded on inserting data on 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 point in iterating the Items list.

public Map<String,AttributeValue> getUser(String email) {

    Map<String,String> expressionAttributesNames = new HashMap<>();
    expressionAttributesNames.put("#email","email");

    Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
    expressionAttributeValues.put(":emailValue",new AttributeValue().withS(email));

    QueryRequest queryRequest = new QueryRequest()
        .withTableName(TABLE_NAME)
        .withKeyConditionExpression("#email = :emailValue")
        .withExpressionAttributeNames(expressionAttributesNames)
        .withExpressionAttributeValues(expressionAttributeValues);

    QueryResult queryResult = amazonDynamoDB.query(queryRequest);

    List<Map<String,AttributeValue>> attributeValues = queryResult.getItems();

    if(attributeValues.size()>0) {
        return attributeValues.get(0);
        } else {
            return null;
        }
    }


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

    public List<Map<String ,AttributeValue>> queryLoginsBetween(String email, Date from, Date to) {

    List<Map<String,AttributeValue>> items = new ArrayList<>();

    Map<String,String> expressionAttributesNames = new HashMap<>();
    expressionAttributesNames.put("#email","email");
    expressionAttributesNames.put("#timestamp","timestamp");

    Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
    expressionAttributeValues.put(":emailValue",new AttributeValue().withS(email));
    expressionAttributeValues.put(":from",new AttributeValue().withN(Long.toString(from.getTime())));
    expressionAttributeValues.put(":to",new AttributeValue().withN(Long.toString(to.getTime())));

    QueryRequest queryRequest = new QueryRequest()
            .withTableName(TABLE_NAME)
            .withKeyConditionExpression("#email = :emailValue and #timestamp BETWEEN :from AND :to ")
            .withExpressionAttributeNames(expressionAttributesNames)
            .withExpressionAttributeValues(expressionAttributeValues);

    Map<String,AttributeValue> lastKey = null;

    do {

            QueryResult queryResult = amazonDynamoDB.query(queryRequest);
            List<Map<String,AttributeValue>> results = queryResult.getItems();
            items.addAll(results);
            lastKey = queryResult.getLastEvaluatedKey();
            } while (lastKey!=null);

        return items;
    }


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. Note that you have to use the last evaluated key to your next request.

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.

public Map<String ,AttributeValue> getSupervisor(String company,String factory) {

    List<Map<String,AttributeValue>> items = new ArrayList<>();

    Map<String,String> expressionAttributesNames = new HashMap<>();
    expressionAttributesNames.put("#company","company");
    expressionAttributesNames.put("#factory","factory");

    Map<String,AttributeValue> expressionAttributeValues = new HashMap<>();
    expressionAttributeValues.put(":company",new AttributeValue().withS(company));
    expressionAttributeValues.put(":factory",new AttributeValue().withS(factory));

    QueryRequest queryRequest = new QueryRequest()
            .withTableName(TABLE_NAME)
            .withKeyConditionExpression("#company = :company and #factory = :factory ")
            .withIndexName("FactoryIndex")
            .withExpressionAttributeNames(expressionAttributesNames)
            .withExpressionAttributeValues(expressionAttributeValues);

    QueryResult queryResult = amazonDynamoDB.query(queryRequest);

    List<Map<String,AttributeValue>> attributeValues = queryResult.getItems();

    if(attributeValues.size()>0) {
        return attributeValues.get(0);
        } else {
            return null;
            }
        }

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

Database

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

Opinions expressed by DZone contributors are their own.

Related

  • Should Developers Switch From SQLite to DuckDB?
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Catching Query Regressions Before Your Users Do

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook