Demonstrate Query on base tables and GSIs, plus Scan.
(client)
| 272 | # --------------------------------------------------------------------------- |
| 273 | |
| 274 | def query_data(client) -> None: |
| 275 | """Demonstrate Query on base tables and GSIs, plus Scan.""" |
| 276 | section("Step 4: Query Data (Query + Scan)") |
| 277 | |
| 278 | # Query base table — all orders for user-001 |
| 279 | resp = client.query( |
| 280 | TableName=ORDERS_TABLE, |
| 281 | KeyConditionExpression="customerId = :cid", |
| 282 | ExpressionAttributeValues={":cid": {"S": "user-001"}}, |
| 283 | ) |
| 284 | print(f" Orders for user-001: {resp['Count']} items") |
| 285 | for item in resp["Items"]: |
| 286 | print(f" {item['orderId']['S']} — ${item['total']['N']} ({item['status']['S']})") |
| 287 | |
| 288 | # Query GSI — orders for user-001 sorted by date |
| 289 | resp = client.query( |
| 290 | TableName=ORDERS_TABLE, |
| 291 | IndexName="OrderDateIndex", |
| 292 | KeyConditionExpression="customerId = :cid AND orderDate BETWEEN :d1 AND :d2", |
| 293 | ExpressionAttributeValues={ |
| 294 | ":cid": {"S": "user-001"}, |
| 295 | ":d1": {"S": "2026-01-01"}, |
| 296 | ":d2": {"S": "2026-12-31"}, |
| 297 | }, |
| 298 | ) |
| 299 | print(f"\n Orders for user-001 in 2026 (via GSI): {resp['Count']} items") |
| 300 | for item in resp["Items"]: |
| 301 | print(f" {item['orderDate']['S']} — {item['orderId']['S']}") |
| 302 | |
| 303 | # Query multi-part GSI — tournament matches in NA region, Spring tournament |
| 304 | resp = client.query( |
| 305 | TableName=TOURNAMENT_TABLE, |
| 306 | IndexName="TournamentRegionIndex", |
| 307 | KeyConditionExpression="tournamentId = :tid AND #r = :region", |
| 308 | ExpressionAttributeNames={"#r": "region"}, |
| 309 | ExpressionAttributeValues={ |
| 310 | ":tid": {"S": "T2026-Spring"}, |
| 311 | ":region": {"S": "NA"}, |
| 312 | }, |
| 313 | ) |
| 314 | print(f"\n Spring tournament NA matches (via multi-part GSI): {resp['Count']} items") |
| 315 | for item in resp["Items"]: |
| 316 | print(f" Match {item['matchId']['S']}: round {item['round']['N']}, bracket {item['bracket']['S']}, score {item['score']['S']}") |
| 317 | |
| 318 | # Query multi-part GSI — player match history |
| 319 | resp = client.query( |
| 320 | TableName=TOURNAMENT_TABLE, |
| 321 | IndexName="PlayerMatchHistoryIndex", |
| 322 | KeyConditionExpression="player1Id = :pid", |
| 323 | ExpressionAttributeValues={":pid": {"S": "user-001"}}, |
| 324 | ) |
| 325 | print(f"\n Match history for user-001 (via PlayerMatchHistoryIndex): {resp['Count']} items") |
| 326 | for item in resp["Items"]: |
| 327 | print(f" {item['matchDate']['S']} — Match {item['matchId']['S']} vs {item['player2Id']['S']}: {item['score']['S']}") |
| 328 | |
| 329 | # Scan — count all users |
| 330 | resp = client.scan(TableName=USERS_TABLE, Select="COUNT") |
| 331 | print(f"\n Total users (Scan COUNT): {resp['Count']}") |