Search in sources :

Example 1 with QueryResult

use of com.amazonaws.services.dynamodbv2.model.QueryResult in project jcabi-dynamo by jcabi.

the class QueryValve method fetch.

// @checkstyle ParameterNumber (5 lines)
@Override
public Dosage fetch(final Credentials credentials, final String table, final Map<String, Condition> conditions, final Collection<String> keys) throws IOException {
    final AmazonDynamoDB aws = credentials.aws();
    try {
        final Collection<String> attrs = new HashSet<String>(Arrays.asList(this.attributes));
        attrs.addAll(keys);
        QueryRequest request = new QueryRequest().withTableName(table).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL).withKeyConditions(conditions).withConsistentRead(this.consistent).withScanIndexForward(this.forward).withSelect(this.select).withLimit(this.limit);
        if (this.select.equals(Select.SPECIFIC_ATTRIBUTES.toString())) {
            request = request.withAttributesToGet(attrs);
        }
        if (!this.index.isEmpty()) {
            request = request.withIndexName(this.index);
        }
        final long start = System.currentTimeMillis();
        final QueryResult result = aws.query(request);
        Logger.info(this, // @checkstyle LineLength (1 line)
        "#items(): loaded %d item(s) from '%s' and stopped at %s, using %s, %s, in %[ms]s", result.getCount(), table, result.getLastEvaluatedKey(), conditions, new PrintableConsumedCapacity(result.getConsumedCapacity()).print(), System.currentTimeMillis() - start);
        return new QueryValve.NextDosage(credentials, request, result);
    } catch (final AmazonClientException ex) {
        throw new IOException(String.format("Failed to fetch from \"%s\" by %s and %s", table, conditions, keys), ex);
    } finally {
        aws.shutdown();
    }
}
Also used : QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) AmazonClientException(com.amazonaws.AmazonClientException) AmazonDynamoDB(com.amazonaws.services.dynamodbv2.AmazonDynamoDB) ToString(lombok.ToString) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 2 with QueryResult

use of com.amazonaws.services.dynamodbv2.model.QueryResult in project jcabi-dynamo by jcabi.

the class QueryValveTest method fetchesData.

/**
 * QueryValve can fetch data from AWS.
 * @throws Exception If some problem inside
 */
@Test
@SuppressWarnings("unchecked")
public void fetchesData() throws Exception {
    final Valve valve = new QueryValve();
    final Credentials credentials = Mockito.mock(Credentials.class);
    final ImmutableMap<String, AttributeValue> item = new ImmutableMap.Builder<String, AttributeValue>().build();
    final AmazonDynamoDB aws = Mockito.mock(AmazonDynamoDB.class);
    Mockito.doReturn(aws).when(credentials).aws();
    Mockito.doReturn(new QueryResult().withItems(Collections.<Map<String, AttributeValue>>singletonList(item)).withConsumedCapacity(new ConsumedCapacity().withCapacityUnits(1.0d))).when(aws).query(Mockito.any(QueryRequest.class));
    final Dosage dosage = valve.fetch(credentials, "table", new Conditions(), new ArrayList<String>(0));
    MatcherAssert.assertThat(dosage.hasNext(), Matchers.is(false));
    MatcherAssert.assertThat(dosage.items(), Matchers.hasItem(item));
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) AmazonDynamoDB(com.amazonaws.services.dynamodbv2.AmazonDynamoDB) ImmutableMap(com.google.common.collect.ImmutableMap) ConsumedCapacity(com.amazonaws.services.dynamodbv2.model.ConsumedCapacity) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) Test(org.junit.Test)

Example 3 with QueryResult

use of com.amazonaws.services.dynamodbv2.model.QueryResult in project aws-doc-sdk-examples by awsdocs.

the class LowLevelGlobalSecondaryIndexExample method queryIndex.

public static void queryIndex(String indexName) {
    System.out.println("\n***********************************************************\n");
    System.out.print("Querying index " + indexName + "...");
    QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withIndexName(indexName).withScanIndexForward(true);
    HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();
    if (indexName == "CreateDateIndex") {
        System.out.println("Issues filed on 2013-11-01");
        keyConditions.put("CreateDate", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("2013-11-01")));
        keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH).withAttributeValueList(new AttributeValue().withS("A-")));
    } else if (indexName == "TitleIndex") {
        System.out.println("Compilation errors");
        keyConditions.put("Title", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("Compilation error")));
        keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH).withAttributeValueList(new AttributeValue().withS("A-")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else if (indexName == "DueDateIndex") {
        System.out.println("Items that are due on 2013-11-30");
        keyConditions.put("DueDate", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("2013-11-30")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else {
        System.out.println("\nNo valid index name provided");
        return;
    }
    queryRequest.setKeyConditions(keyConditions);
    QueryResult result = client.query(queryRequest);
    List<Map<String, AttributeValue>> items = result.getItems();
    Iterator<Map<String, AttributeValue>> itemsIter = items.iterator();
    System.out.println();
    while (itemsIter.hasNext()) {
        Map<String, AttributeValue> currentItem = itemsIter.next();
        Iterator<String> currentItemIter = currentItem.keySet().iterator();
        while (currentItemIter.hasNext()) {
            String attr = (String) currentItemIter.next();
            if (attr == "Priority") {
                System.out.println(attr + "---> " + currentItem.get(attr).getN());
            } else {
                System.out.println(attr + "---> " + currentItem.get(attr).getS());
            }
        }
        System.out.println();
    }
}
Also used : Condition(com.amazonaws.services.dynamodbv2.model.Condition) AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with QueryResult

use of com.amazonaws.services.dynamodbv2.model.QueryResult in project aws-doc-sdk-examples by awsdocs.

the class LowLevelLocalSecondaryIndexExample method query.

public static void query(String indexName) {
    System.out.println("\n***********************************************************\n");
    System.out.println("Querying table " + tableName + "...");
    QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withConsistentRead(true).withScanIndexForward(true).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);
    HashMap<String, Condition> keyConditions = new HashMap<String, Condition>();
    keyConditions.put("CustomerId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS("bob@example.com")));
    if (indexName == "IsOpenIndex") {
        System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open.");
        System.out.println("Only a user-specified list of attributes are returned\n");
        queryRequest.setIndexName(indexName);
        keyConditions.put("IsOpen", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withN("1")));
        // ProjectionExpression
        queryRequest.setProjectionExpression("OrderCreationDate, ProductCategory, ProductName, OrderStatus");
    } else if (indexName == "OrderCreationDateIndex") {
        System.out.println("\nUsing index: '" + indexName + "': Bob's orders that were placed after 01/31/2013.");
        System.out.println("Only the projected attributes are returned\n");
        queryRequest.setIndexName(indexName);
        keyConditions.put("OrderCreationDate", new Condition().withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(new AttributeValue().withN("20130131")));
        // Select
        queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES);
    } else {
        System.out.println("\nNo index: All of Bob's orders, by OrderId:\n");
    }
    queryRequest.setKeyConditions(keyConditions);
    QueryResult result = client.query(queryRequest);
    List<Map<String, AttributeValue>> items = result.getItems();
    Iterator<Map<String, AttributeValue>> itemsIter = items.iterator();
    while (itemsIter.hasNext()) {
        Map<String, AttributeValue> currentItem = itemsIter.next();
        Iterator<String> currentItemIter = currentItem.keySet().iterator();
        while (currentItemIter.hasNext()) {
            String attr = (String) currentItemIter.next();
            if (attr == "OrderId" || attr == "IsOpen" || attr == "OrderCreationDate") {
                System.out.println(attr + "---> " + currentItem.get(attr).getN());
            } else {
                System.out.println(attr + "---> " + currentItem.get(attr).getS());
            }
        }
        System.out.println();
    }
    System.out.println("\nConsumed capacity: " + result.getConsumedCapacity() + "\n");
}
Also used : Condition(com.amazonaws.services.dynamodbv2.model.Condition) AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with QueryResult

use of com.amazonaws.services.dynamodbv2.model.QueryResult in project aws-doc-sdk-examples by awsdocs.

the class LowLevelQuery method findRepliesForAThreadSpecifyOptionalLimit.

private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {
    Map<String, AttributeValue> lastEvaluatedKey = null;
    do {
        QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(makeReplyKeyConditions(forumName, threadSubject)).withLimit(1).withExclusiveStartKey(lastEvaluatedKey);
        QueryResult result = client.query(queryRequest);
        for (Map<String, AttributeValue> item : result.getItems()) {
            printItem(item);
        }
        lastEvaluatedKey = result.getLastEvaluatedKey();
    } while (lastEvaluatedKey != null);
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) QueryResult(com.amazonaws.services.dynamodbv2.model.QueryResult) QueryRequest(com.amazonaws.services.dynamodbv2.model.QueryRequest)

Aggregations

QueryResult (com.amazonaws.services.dynamodbv2.model.QueryResult)13 QueryRequest (com.amazonaws.services.dynamodbv2.model.QueryRequest)12 AttributeValue (com.amazonaws.services.dynamodbv2.model.AttributeValue)10 HashMap (java.util.HashMap)7 Condition (com.amazonaws.services.dynamodbv2.model.Condition)6 AmazonDynamoDB (com.amazonaws.services.dynamodbv2.AmazonDynamoDB)4 Map (java.util.Map)3 AmazonClientException (com.amazonaws.AmazonClientException)2 ConsumedCapacity (com.amazonaws.services.dynamodbv2.model.ConsumedCapacity)2 IOException (java.io.IOException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 AmazonDynamoDBException (com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 HashSet (java.util.HashSet)1 ToString (lombok.ToString)1 Test (org.junit.Test)1