AWS SDK Version 3 for .NET
API Reference

AWS services or capabilities described in AWS Documentation may vary by region/location. Click Getting Started with Amazon AWS to see specific differences applicable to the China (Beijing) Region.

You must provide the name of the partition key attribute and a single value for that attribute. Query returns all items with that partition key value. Optionally, you can provide a sort key attribute and use a comparison operator to refine the search results.

Use the KeyConditionExpression parameter to provide a specific value for the partition key. The Query operation will return all of the items from the table or index with that partition key value. You can optionally narrow the scope of the Query operation by specifying a sort key value and a comparison operator in KeyConditionExpression. To further refine the Query results, you can optionally provide a FilterExpression. A FilterExpression determines which items within the results should be returned to you. All of the other results are discarded.

A Query operation always returns a result set. If no matching items are found, the result set will be empty. Queries that do not return results consume the minimum number of read capacity units for that type of read operation.

DynamoDB calculates the number of read capacity units consumed based on item size, not on the amount of data that is returned to an application. The number of capacity units consumed will be the same whether you request all of the attributes (the default behavior) or just some of them (using a projection expression). The number will also be the same whether or not you use a FilterExpression.

Query results are always sorted by the sort key value. If the data type of the sort key is Number, the results are returned in numeric order; otherwise, the results are returned in order of UTF-8 bytes. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false.

A single Query operation will read up to the maximum number of items set (if using the Limit parameter) or a maximum of 1 MB of data and then apply any filtering to the results using FilterExpression. If LastEvaluatedKey is present in the response, you will need to paginate the result set. For more information, see Paginating the Results in the Amazon DynamoDB Developer Guide.

FilterExpression is applied after a Query finishes, but before the results are returned. A FilterExpression cannot contain partition key or sort key attributes. You need to specify those attributes in the KeyConditionExpression.

A Query operation can return an empty result set and a LastEvaluatedKey if all the items read for the page of results are filtered out.

You can query a table, a local secondary index, or a global secondary index. For a query on a table or on a local secondary index, you can set the ConsistentRead parameter to true and obtain a strongly consistent result. Global secondary indexes support eventually consistent reads only, so do not specify ConsistentRead when querying a global secondary index.

Note:

For .NET Core this operation is only available in asynchronous form. Please refer to QueryAsync.

Namespace: Amazon.DynamoDBv2
Assembly: AWSSDK.DynamoDBv2.dll
Version: 3.x.y.z

Syntax

C#
public virtual QueryResponse Query(
         QueryRequest request
)

Parameters

request
Type: Amazon.DynamoDBv2.Model.QueryRequest

Container for the necessary parameters to execute the Query service method.

Return Value


The response from the Query service method, as returned by DynamoDB.

Exceptions

ExceptionCondition
InternalServerErrorException An error occurred on the server side.
ProvisionedThroughputExceededException Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to Error Retries and Exponential Backoff in the Amazon DynamoDB Developer Guide.
RequestLimitExceededException Throughput exceeds the current throughput quota for your account. Please contact Amazon Web Services Support to request a quota increase.
ResourceNotFoundException The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be ACTIVE.

Examples

The following example shows how to query items in a table.
Note: the Query operation retrieves items that have the same hash-key. This means that the Query operation is only supported on tables with both a hash- and a range-key.
Note: the RangeKeyCondition for Query is limited to indexable comparisons. These are EQ, LE, LT, GE, GT, BETWEEN, and BEGINS_WITH.
We will now retrieve all items where the hash-key is "Mark Twain" and the range-key begins with the string "The Adventures".

Query sample


// Create a client
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

// Define item hash-key to be string value "Mark Twain"
AttributeValue hashKey = new AttributeValue { S = "Mark Twain" };

// Define query condition to search for range-keys that begin with the string "The Adventures"
Condition condition = new Condition
{
    ComparisonOperator = "BEGINS_WITH",
    AttributeValueList = new List<AttributeValue>
    {
        new AttributeValue { S = "The Adventures" }
    }
};

// Create the key conditions from hashKey and condition
Dictionary<string, Condition> keyConditions = new Dictionary<string, Condition>
{
    // Hash key condition. ComparisonOperator must be "EQ".
    { 
        "Author",
        new Condition
        {
            ComparisonOperator = "EQ",
            AttributeValueList = new List<AttributeValue> { hashKey }
        }
    },
    // Range key condition
    {
        "Title",
        condition
    }
};

// Define marker variable
Dictionary<string, AttributeValue> startKey = null;

do
{
    // Create Query request
    QueryRequest request = new QueryRequest
    {
        TableName = "SampleTable",
        ExclusiveStartKey = startKey,
        KeyConditions = keyConditions
    };

    // Issue request
    var result = client.Query(request);

    // View all returned items
    List<Dictionary<string, AttributeValue>> items = result.Items;
    foreach (Dictionary<string, AttributeValue> item in items)
    {
        Console.WriteLine("Item:");
        foreach (var keyValuePair in item)
        {
            Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]",
                keyValuePair.Key,
                keyValuePair.Value.S,
                keyValuePair.Value.N,
                string.Join(", ", keyValuePair.Value.SS ?? new List<string>()),
                string.Join(", ", keyValuePair.Value.NS ?? new List<string>()));
        }
    }

    // Set marker variable
    startKey = result.LastEvaluatedKey;
} while (startKey != null && startKey.Count > 0);

                

The following example shows how to query items in a local secondary index.
Like a standard Query, we must pass in a hash-key value. But since we are querying against a specific index, we must remember to refer to the correct index attribute.
In the below example that means that we reference the attribute "Years", and since the attribute is numerical we must pass in a numerical AttributeValue.


// Create a client
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

// Define item hash-key to be string value "Mark Twain"
AttributeValue hashKey = new AttributeValue { S = "Mark Twain" };

// Define query condition to search for range-keys ("Year", in "YearsIndex") that are less than 1900
Condition condition = new Condition
{
    ComparisonOperator = "LT",
    AttributeValueList = new List<AttributeValue>
    {
        new AttributeValue { N = "1900" }
    }
};

// Create the key conditions from hashKey and condition
Dictionary<string, Condition> keyConditions = new Dictionary<string, Condition>
{
    // Hash key condition. ComparisonOperator must be "EQ".
    { 
        "Author",
        new Condition
        {
            ComparisonOperator = "EQ",
            AttributeValueList = new List<AttributeValue> { hashKey }
        }
    },
    // Range key condition
    {
        "Year", // Reference the correct range key when using indexes
        condition
    }
};

// Define marker variable
Dictionary<string, AttributeValue> startKey = null;

do
{
    // Create Query request
    QueryRequest request = new QueryRequest
    {
        TableName = "SampleTable",
        ExclusiveStartKey = startKey,
        KeyConditions = keyConditions,
        IndexName = "YearsIndex" // Specify the index to query against
    };

    // Issue request
    var result = client.Query(request);

    // View all returned items
    List<Dictionary<string, AttributeValue>> items = result.Items;
    foreach (Dictionary<string, AttributeValue> item in items)
    {
        Console.WriteLine("Item:");
        foreach (var keyValuePair in item)
        {
            Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]",
                keyValuePair.Key,
                keyValuePair.Value.S,
                keyValuePair.Value.N,
                string.Join(", ", keyValuePair.Value.SS ?? new List<string>()),
                string.Join(", ", keyValuePair.Value.NS ?? new List<string>()));
        }
    }

    // Set marker variable
    startKey = result.LastEvaluatedKey;
} while (startKey != null && startKey.Count > 0);

                

Version Information

.NET Framework:
Supported in: 4.5, 4.0, 3.5

See Also