Dynamodb query java

Dynamodb query java DEFAULT

The CloudStorageMaven Guide

On a previous post we proceeded on inserting data on a DynamoDB database.

On 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 on 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.
Logins Table suits well for an example. We will issue a query that will fetch login attempts between to 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(); queryRequest.setExclusiveStartKey(lastKey); } 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 case of multiple pages. Therefore 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.

I’ve compiled a cheat sheet that lists dynamodb functions in Java
Sign up in the link to receive it.

Like this:

LikeLoading...

Related

Published

Sours: https://egkatzioura.com/2016/07/02/query-dynamodb-items-with-java/

Step 4: Query and Scan the Data

You can use the method to retrieve data from a table. You must specify a partition key value. The sort key is optional.

The primary key for the table is composed of the following:

  • – The partition key. The attribute type is number.

  • – The sort key. The attribute type is string.

To find all movies released during a year, you need to specify only the . You can also provide the to retrieve a subset of movies based on some condition (on the sort key). For example, you can find movies released in 2014 that have a title starting with the letter "A".

In addition to the method, there is also a method that can retrieve all of the table data.

To learn more about querying and scanning data, see Working with Queries in DynamoDB and Working with Scans in DynamoDB, respectively.

Step 4.1: Query

The code included in this step performs the following queries:

  • Retrieve all movies released in the 1985.

  • Retrieve all movies released in the 1992, with a beginning with the letter "A" through the letter "L".

  1. Copy the following program and paste it into your Java development environment.

    Note

    • provides name substitution. This is used because is a reserved word in Amazon DynamoDB. You can't use it directly in any expression, including . You use the expression attribute name to address this.

    • provides value substitution. This is used because you can't use literals in any expression, including . You use the expression attribute value to address this.

    First, you create the object, which describes the query parameters, and then you pass the object to the method.

  2. Compile and run the program.

Note

The preceding program shows how to query a table by its primary key attributes. In DynamoDB, you can optionally create one or more secondary indexes on a table, and query those indexes in the same way that you query a table. Secondary indexes give your applications additional flexibility by allowing queries on non-key attributes. For more information, see Improving Data Access with Secondary Indexes.

Step 4.2: Scan

The method reads every item in the entire table and returns all the data in the table. You can provide an optional so that only the items matching your criteria are returned. However, the filter is applied only after the entire table has been scanned.

The following program scans the entire table, which contains approximately 5,000 items. The scan specifies the optional filter to retrieve only the movies from the 1950s (approximately 100 items) and discard all the others.

  1. Copy the following program and paste it into your Java development environment.

    In the code, note the following:

    • specifies the attributes you want in the scan result.

    • specifies a condition that returns only items that satisfy the condition. All other items are discarded.

  2. Compile and run the program.

Document Conventions

Step 3: Create, Read, Update, and Delete an Item

Step 5: (Optional) Delete the Table

Sours: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Java.04.html
  1. Original sylvanas model
  2. Fender journeyman relic
  3. Eastern flooring reviews
  4. Msi servicenow
  5. Picture of theodd1sout

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.

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.

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.

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

Sours: https://dzone.com/articles/query-dynamodb-items-withjava
Amazon DynamoDB Using Java

Querying Tables and Indexes: Java

The operation enables you to query a table or a secondary index in Amazon DynamoDB. You must provide a partition key value and an equality condition. If the table or index has a sort key, you can refine the results by providing a sort key value and a condition.

Note

The AWS SDK for Java also provides an object persistence model, enabling you to map your client-side classes to DynamoDB tables. This approach can reduce the amount of code you have to write. For more information, see Java: DynamoDBMapper.

The following are the steps to retrieve an item using the AWS SDK for Java Document API.

  1. Create an instance of the class.

  2. Create an instance of the class to represent the table you want to work with.

  3. Call the method of the instance. You must specify the partition key value of the items that you want to retrieve, along with any optional query parameters.

The response includes an object that provides all items returned by the query.

The following Java code example demonstrates the preceding tasks. The example assumes that you have a table that stores replies for forum threads. For more information, see Creating Tables and Loading Data for Code Examples in DynamoDB.

Each forum thread has a unique ID and can have zero or more replies. Therefore, the attribute of the table is composed of both the forum name and forum subject. (partition key) and (sort key) make up the composite primary key for the table.

The following query retrieves all replies for a specific thread subject. The query requires both the table name and the value.

Example

Specifying Optional Parameters

The method supports several optional parameters. For example, you can optionally narrow the results from the preceding query to return replies in the past two weeks by specifying a condition. The condition is called a sort key condition, because DynamoDB evaluates the query condition that you specify against the sort key of the primary key. You can specify other optional parameters to retrieve only a specific list of attributes from items in the query result.

The following Java code example retrieves forum thread replies posted in the past 15 days. The example specifies optional parameters using the following:

  • A to retrieve the replies from a specific discussion forum (partition key) and, within that set of items, replies that were posted within the last 15 days (sort key).

  • A to return only the replies from a specific user. The filter is applied after the query is processed, but before the results are returned to the user.

  • A to define the actual values for the placeholders.

  • A setting of true, to request a strongly consistent read.

This example uses a object that gives access to all of the low-level input parameters.

Example

You can also optionally limit the number of items per page by using the method. When you call the method, you get an that contains the resulting items. You can then step through the results, processing one page at a time, until there are no more pages.

The following Java code example modifies the query specification shown previously. This time, the query spec uses the method. The class provides an iterator that allows the code to process the items on each page.

Example

Example - Query Using Java

The following tables store information about a collection of forums. For more information, see Creating Tables and Loading Data for Code Examples in DynamoDB.

Note

The SDK for Java also provides an object persistence model, enabling you to map your client-side classes to DynamoDB tables. This approach can reduce the amount of code you have to write. For more information, see Java: DynamoDBMapper.

Example

In this Java code example, you run variations of finding replies for a thread "DynamoDB Thread 1" in forum "DynamoDB".

  • Find replies for a thread.

  • Find replies for a thread, specifying a limit on the number of items per page of results. If the number of items in the result set exceeds the page size, you get only the first page of results. This coding pattern ensures that your code processes all the pages in the query result.

  • Find replies in the last 15 days.

  • Find replies in a specific date range.

    The preceding two queries show how you can specify sort key conditions to narrow the query results and use other optional query parameters.

Sours: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryingJavaDocumentAPI.html

Java dynamodb query

Querying DynamoDB in Java with the AWS SDK 2.0

Queries in DynamoDB allow you to find data. This is only an option to you if your table has a partition and sort key.

This post will demonstrate a couple different ways to get querying to work in java, using the AWS SDK v2, with full reactive support. The source code is available on Github.

Setting up the data

We will be building off of a previous post that set up an in memory [embedded] dynamo instance to save us time and energy. In that post, if you recall, we had a hash key named "Company" and a range key named "Phones", which presumably is to store a catalog of different companies that manufacture different phones.

We will follow the same pattern as before where we are writing an integration test to describe much of this behavior. First, let's set up some metadata and create this table:

The method mentioned here to create the table looks contains code like this, and is probably only relevant for setting up tests like this [I would recommend using something like terraform to manage dynamo tables in the cloud, rather than java code]:

Alright, so now we've got our table, we're going to create three items, each with the same partition key as Google. The range keys will be Pixel 1, Pixel 2, and Future Phone:

And I'll note again some helper methods outlined above:

With this in place, let's demonstrate querying.

Querying Now

To start with, we have to provide at least one partition key in a Key Condition Expression. In this case we also have a range key, so specifying just the partition key will grab all of the range keys:

Here, we get all of the items associated with a particular partition key, which as a reminder in this case is Google, and then we assert that we get three items back and that at least one of them has a Year attribute of 2012. This part of the test passes.

Let's do one more. Let's say we want to get all the models of the phones produced by Google that were of the Pixel family. Assuming we are versioning all the Pixel phones such that they start with the word "Pixel", we can do the following:

And with that, you should have a good starting point for experimenting more yourself. Reminder that you can check out the source code for this post on github

Nick Fisher is a software engineer in the Pacific Northwest. He focuses on building highly scalable and maintainable backend systems.

Sours: https://nickolasfisher.com/blog/Querying-DynamoDB-in-Java-with-the-AWS-SDK-20
AWS DynamoDB - How to Perform operation on DynamoDB through Java Code - Part2

Best Java code snippets using com.amazonaws.services.dynamodbv2.AmazonDynamoDB.query(Showing top 20 results out of 315)

  • Common ways to obtain AmazonDynamoDB

    private void myMethod () {

    }

    @Override public Page<Item,QueryOutcome> nextPage() { if (lastEvaluatedKey == null) { thrownew NoSuchElementException("No more pages"); } final Integer max = spec.getMaxResultSize(); if (max != null) { int nextLimit = nextRequestLimit(max.intValue()); if (nextLimit == 0) thrownew NoSuchElementException("No more pages"); request.setLimit(nextLimit); } request.setExclusiveStartKey(lastEvaluatedKey); QueryResult result = client.query(request); finalint nextIndex = index + this.size(); returnnew QueryPage(client, spec, request, nextIndex, new QueryOutcome(result)); } }
    @Override public <T> PaginatedQueryList<T> query(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); QueryResult queryResult = db.query(applyUserAgent(queryRequest)); returnnew PaginatedQueryList<T>(this, clazz, db, queryRequest, queryResult, config.getPaginationLoadingStrategy(), config); }
    @Override protectedsynchronized List<T> fetchNextPage() { queryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); queryResult = dynamo.query(DynamoDBMapper.applyUserAgent(queryRequest)); return mapper.marshallIntoObjects(mapper.toParameters( queryResult.getItems(), clazz, queryRequest.getTableName(), config)); } }
    @Override public Page<Item, QueryOutcome> firstPage() { QueryRequest request = spec.getRequest(); request.setExclusiveStartKey(startKey); request.setLimit(InternalUtils.minimum( spec.getMaxResultSize(), spec.getMaxPageSize())); QueryResult result = client.query(request); QueryOutcome outcome = new QueryOutcome(result); setLastLowLevelResult(outcome); returnnew QueryPage(client, spec, request, 0, outcome); }
    @Override public <T> int count(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); queryRequest.setSelect(Select.COUNT); int count = 0; QueryResult queryResult = null; do { queryResult = db.query(applyUserAgent(queryRequest)); count += queryResult.getCount(); queryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); } while (queryResult.getLastEvaluatedKey() != null); return count; }
    @Override public <T> QueryResultPage<T> queryPage(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); QueryResult queryResult = db.query(applyUserAgent(queryRequest)); QueryResultPage<T> result = new QueryResultPage<T>(); List<AttributeTransformer.Parameters<T>> parameters = toParameters(queryResult.getItems(), clazz, queryRequest.getTableName(), config); result.setResults(marshallIntoObjects(parameters)); result.setLastEvaluatedKey(queryResult.getLastEvaluatedKey()); result.setCount(queryResult.getCount()); result.setScannedCount(queryResult.getScannedCount()); result.setConsumedCapacity(queryResult.getConsumedCapacity()); return result; }
    @Override protectedsynchronized List<T> fetchNextPage() { queryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); queryResult = dynamo.query(DynamoDBMapper.applyUserAgent(queryRequest)); return mapper.marshallIntoObjects(mapper.toParameters( queryResult.getItems(), clazz, queryRequest.getTableName(), config)); } }
    final QueryResult queryResult = db.query(applyUserAgent(queryRequest)); returnnew PaginatedQueryList<T>(this, clazz, db, queryRequest, queryResult, config.getPaginationLoadingStrategy(), config);
    final QueryResult result = table.getClient().query(request); for (final Map<String, AttributeValue> item : result.getItems()) { final Document doc = Document.fromAttributeMap(item);
    public <T> int count(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); final QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); queryRequest.setSelect(Select.COUNT); int count = 0; QueryResult queryResult = null; do { queryResult = db.query(applyUserAgent(queryRequest)); count += queryResult.getCount(); queryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); } while (queryResult.getLastEvaluatedKey() != null); return count; }
    public <T> QueryResultPage<T> queryPage(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); final QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); final QueryResult scanResult = db.query(applyUserAgent(queryRequest)); final QueryResultPage<T> result = new QueryResultPage<T>(); final List<AttributeTransformer.Parameters<T>> parameters = toParameters(scanResult.getItems(), clazz, queryRequest.getTableName(), config); result.setResults(marshallIntoObjects(parameters)); result.setLastEvaluatedKey(scanResult.getLastEvaluatedKey()); return result; }
    final QueryResult result = table.getClient().query(request); count = this.matches.size() + result.getCount(); return count;
    @Override public QueryResult query(QueryRequest request) throws AmazonServiceException, AmazonClientException { return getBackend().query(request); }
    @Override public <T> PaginatedQueryList<T> query(Class<T> clazz, QueryRequest queryRequest) { QueryResult queryResult = amazonDynamoDB.query(queryRequest); returnnew PaginatedQueryList<T>(dynamoDBMapper, clazz, amazonDynamoDB, queryRequest, queryResult, dynamoDBMapperConfig.getPaginationLoadingStrategy(), dynamoDBMapperConfig); }
    @Override public <T> PaginatedQueryList<T> query(Class<T> clazz, QueryRequest queryRequest) { QueryResult queryResult = amazonDynamoDB.query(queryRequest); returnnew PaginatedQueryList<T>(dynamoDBMapper, clazz, amazonDynamoDB, queryRequest, queryResult, dynamoDBMapperConfig.getPaginationLoadingStrategy(), dynamoDBMapperConfig); }
    @Override public <T> PaginatedQueryList<T> query(Class<T> clazz, DynamoDBQueryExpression<T> queryExpression, DynamoDBMapperConfig config) { config = mergeConfig(config); QueryRequest queryRequest = createQueryRequestFromExpression(clazz, queryExpression, config); QueryResult queryResult = db.query(applyUserAgent(queryRequest)); returnnew PaginatedQueryList<T>(this, clazz, db, queryRequest, queryResult, config.getPaginationLoadingStrategy(), config); }
    @Override public <T> int count(Class<T> clazz, QueryRequest mutableQueryRequest) { mutableQueryRequest.setSelect(Select.COUNT); int count = 0; QueryResult queryResult = null; do { queryResult = amazonDynamoDB.query(mutableQueryRequest); count += queryResult.getCount(); mutableQueryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); } while (queryResult.getLastEvaluatedKey() != null); return count; }
    @Override protectedsynchronized List<T> fetchNextPage() { queryRequest.setExclusiveStartKey(queryResult.getLastEvaluatedKey()); queryResult = dynamo.query(DynamoDBMapper.applyUserAgent(queryRequest)); return mapper.marshallIntoObjects(mapper.toParameters( queryResult.getItems(), clazz, queryRequest.getTableName(), config)); } }
    @Override public QueryResult query(QueryRequest request) throws AmazonServiceException, AmazonClientException { Collection<String> attributesToGet = addSpecialAttributes(request.getAttributesToGet()); request.setAttributesToGet(attributesToGet); QueryResult result = txManager.getClient().query(request); List<Map<String, AttributeValue>> items = handleItems(result.getItems(), request.getTableName(), request.getAttributesToGet()); result.setItems(items); return result; }
    @Override public Page<Item, QueryOutcome> firstPage() { QueryRequest request = spec.getRequest(); request.setExclusiveStartKey(startKey); request.setLimit(InternalUtils.minimum( spec.getMaxResultSize(), spec.getMaxPageSize())); QueryResult result = client.query(request); QueryOutcome outcome = new QueryOutcome(result); setLastLowLevelResult(outcome); returnnew QueryPage(client, spec, request, 0, outcome); }
    Sours: https://www.tabnine.com/code/java/methods/com.amazonaws.services.dynamodbv2.AmazonDynamoDB/query

    Now discussing:

    DynamoDB - Querying



    Queries locate items or secondary indices through primary keys. Performing a query requires a partition key and specific value, or a sort key and value; with the option to filter with comparisons. The default behavior of a query consists of returning every attribute for items associated with the provided primary key. However, you can specify the desired attributes with the ProjectionExpression parameter.

    A query utilizes the KeyConditionExpression parameters to select items, which requires providing the partition key name and value in the form of an equality condition. You also have the option to provide an additional condition for any sort keys present.

    A few examples of the sort key conditions are −

    Sr.NoCondition & Description
    1

    x = y

    It evaluates to true if the attribute x equals y.

    2

    x < y

    It evaluates to true if x is less than y.

    3

    x <= y

    It evaluates to true if x is less than or equal to y.

    4

    x > y

    It evaluates to true if x is greater than y.

    5

    x >= y

    It evaluates to true if x is greater than or equal to y.

    6

    x BETWEEN y AND z

    It evaluates to true if x is both >= y, and <= z.

    DynamoDB also supports the following functions: begins_with (x, substr)

    It evaluates to true if attribute x starts with the specified string.

    The following conditions must conform to certain requirements −

    • Attribute names must start with a character within the a-z or A-Z set.

    • The second character of an attribute name must fall in the a-z, A-Z, or 0-9 set.

    • Attribute names cannot use reserved words.

    Attribute names out of compliance with the constraints above can define a placeholder.

    The query processes by performing retrievals in sort key order, and using any condition and filter expressions present. Queries always return a result set, and on no matches, it returns an empty one.

    The results always return in sort key order, and data type based order with the modifiable default as the ascending order.

    Querying with Java

    Queries in Java allow you to query tables and secondary indices. They require specification of partition keys and equality conditions, with the option to specify sort keys and conditions.

    The general required steps for a query in Java include creating a DynamoDB class instance, Table class instance for the target table, and calling the query method of the Table instance to receive the query object.

    The response to the query contains an ItemCollection object providing all the returned items.

    The following example demonstrates detailed querying −

    DynamoDB dynamoDB = new DynamoDB ( new AmazonDynamoDBClient(new ProfileCredentialsProvider())); Table table = dynamoDB.getTable("Response"); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("ID = :nn") .withValueMap(new ValueMap() .withString(":nn", "Product Line 1#P1 Thread 1")); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); Item item = null; while (iterator.hasNext()) { item = iterator.next(); System.out.println(item.toJSONPretty()); }

    The query method supports a wide variety of optional parameters. The following example demonstrates how to utilize these parameters −

    Table table = dynamoDB.getTable("Response"); QuerySpec spec = new QuerySpec() .withKeyConditionExpression("ID = :nn and ResponseTM > :nn_responseTM") .withFilterExpression("Author = :nn_author") .withValueMap(new ValueMap() .withString(":nn", "Product Line 1#P1 Thread 1") .withString(":nn_responseTM", twoWeeksAgoStr) .withString(":nn_author", "Member 123")) .withConsistentRead(true); ItemCollection<QueryOutcome> items = table.query(spec); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); }

    You can also review the following larger example.

    Note − The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).

    This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.

    package com.amazonaws.codesamples.document; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.Page; import com.amazonaws.services.dynamodbv2.document.QueryOutcome; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; public class QueryOpSample { static DynamoDB dynamoDB = new DynamoDB( new AmazonDynamoDBClient(new ProfileCredentialsProvider())); static String tableName = "Reply"; public static void main(String[] args) throws Exception { String forumName = "PolyBlaster"; String threadSubject = "PolyBlaster Thread 1"; getThreadReplies(forumName, threadSubject); } private static void getThreadReplies(String forumName, String threadSubject) { Table table = dynamoDB.getTable(tableName); String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec() .withKeyConditionExpression("Id = :v_id") .withValueMap(new ValueMap() .withString(":v_id", replyId)); ItemCollection<QueryOutcome> items = table.query(spec); System.out.println("\ngetThreadReplies results:"); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); } } }
    Sours: https://www.tutorialspoint.com/dynamodb/dynamodb_querying.htm


    323 324 325 326 327