Skip to main content

DynamoDB Query and Scan in C#

Query and scan DynamoDB tables efficiently using FluentDynamoDB. This guide demonstrates partition key queries, sort key conditions, and filter expressions across all three API patterns.

Query by Partition Key

// Get all orders for a customer
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == "customer123")
.ToListAsync();

Sort Key Conditions

// Orders after a specific date
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId && x.OrderId > "ORDER#2024-01-01")
.ToListAsync();

// Orders within a date range
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId &&
x.OrderId.Between("ORDER#2024-01", "ORDER#2024-12"))
.ToListAsync();

// Orders with a prefix
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId && x.OrderId.StartsWith("ORDER#2024-03"))
.ToListAsync();

Filter Expressions

// Filter by status
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId)
.WithFilter(x => x.Status == "pending")
.ToListAsync();

// Multiple filter conditions
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId)
.WithFilter(x => x.Status == "pending" && x.Total > 100.00m)
.ToListAsync();

// OR conditions
var orders = await table.Query<Order>()
.Where(x => x.CustomerId == customerId)
.WithFilter(x => x.Status == "pending" || x.Status == "processing")
.ToListAsync();

Query on GSI

// Query orders by status using a GSI
var orders = await table.Query<Order>()
.UsingIndex("StatusIndex")
.Where(x => x.Status == "pending")
.ToListAsync();

Scan with Filter

// Scan requires [Scannable] attribute on entity
var users = await table.Users.Scan()
.WithFilter(x => x.Premium || x.Score >= 1000)
.ToListAsync();

Entity Definition

All examples above use this entity definition:

[DynamoDbTable("orders")]
public partial class Order
{
[PartitionKey]
[DynamoDbAttribute("pk")]
public string CustomerId { get; set; } = string.Empty;

[SortKey]
[DynamoDbAttribute("sk")]
public string OrderId { get; set; } = string.Empty;

[GsiPartitionKey("StatusIndex")]
[DynamoDbAttribute("status")]
public string Status { get; set; } = "pending";

[DynamoDbAttribute("total")]
public decimal Total { get; set; }
}

Key Concepts

ConceptDescription
Where()Key condition for partition key and sort key (efficient, reduces read capacity)
WithFilter()Filter expression applied after items are read (reduces data transfer, not read capacity)
UsingIndex()Query on a Global Secondary Index (GSI)
Scan()Read all items in a table (requires [Scannable] attribute, use sparingly)

Learn More