如何通过DynamoDB CLI查询sw为空数组的对象?报错解决
Let’s break down what’s going wrong and how to fix your issue:
Why Your Original query Command Failed
DynamoDB’s query operation only works against the table’s primary key (partition key + optional sort key) or a global secondary index (GSI) key. You tried to query directly on the sw attribute, which isn’t part of your table’s key schema—this is exactly why you got the ValidationException saying "Query condition missed key schema element."
Quick Fix: Use scan with a Filter Expression
For small datasets (like your local table with 2 items), the simplest solution is to use scan paired with a FilterExpression to narrow down results to items where sw is an empty list.
Direct Command Line Example:
aws dynamodb scan \ --table-name "hotel" \ --filter-expression "attribute_exists(sw) AND size(sw) = :empty" \ --expression-attribute-values '{":empty": {"N": "0"}}' \ --endpoint-url http://localhost:8088
Using a JSON Configuration File (e.g., filter-config.json):
Create this file in your tables directory:
{ "FilterExpression": "attribute_exists(sw) AND size(sw) = :empty", "ExpressionAttributeValues": { ":empty": {"N": "0"} } }
Then run the command:
aws dynamodb scan --table-name "hotel" --cli-input-json file://tables/filter-config.json --endpoint-url http://localhost:8088
Better Long-Term Solution: Create a GSI for sw
If you plan to run this query frequently or have a larger dataset, creating a Global Secondary Index (GSI) on the sw attribute lets you use query instead of scan (which is more efficient for repeated use).
- Add the GSI to your table:
aws dynamodb update-table \ --table-name "hotel" \ --attribute-definitions AttributeName=sw,AttributeType=L \ --global-secondary-indexes '[{"IndexName": "sw-index", "KeySchema": [{"AttributeName": "sw", "KeyType": "HASH"}], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}}]' \ --endpoint-url http://localhost:8088
(Note: For local DynamoDB, low throughput values work fine; adjust for production based on your needs.)
- Query the GSI once it’s active:
aws dynamodb query \ --table-name "hotel" \ --index-name "sw-index" \ --key-condition-expression "sw = :empty_list" \ --expression-attribute-values '{":empty_list": {"L": []}}' \ --endpoint-url http://localhost:8088
Quick Note on Filter Logic
attribute_exists(sw)ensures we only target items that actually have theswattribute (avoids matching items whereswis missing entirely).size(sw) = :emptychecks that the list has zero elements (i.e., it’s empty).
内容的提问来源于stack exchange,提问作者Rudrani Angira

