Reputation: 171
I want to query my DynamoDB with a lambda function running python.
DynamoDB Table (Name: Testing-Table):
I want to query the table as it is in my code. I want the lambda function to return me all the user_id's that has their status attribute with active.
table = dynamodb.Table('Testing-Table')
def lambda_handler(event, context):
response = table.query (
KeyConditionExpression=Key('status').eq('active')
)
for i in response['Items']:
print(i['user_id'],":",i['status'])
#return 'listing results'
I've also added a new index:
I tried creating a table with status as primary key, and my code worked... but primarykey's must be unique, so when I try to create a new item in my table, I cant set status as active again.
If necessary, I will add more information to the question. I would thank for a little help.
--Edit-- My code works only if status is the PrimaryKey of my table.
My question is: Can I query my DynamoDB table using status PartitionKey instead of the PrimaryKey used_id? And most important...How is it done?
Upvotes: 6
Views: 5062
Reputation: 93
An alternative method exists for locating items without relying on the partition key or sort key. If you're interested in understanding the functionality of these keys, you can refer to this source.
The previous solution utilized the table.query function. However, this solution will employ the table.scan function. For further information on scanning, you can consult the official documentation here.
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('table_name')
response = table.scan(
FilterExpression=Attr('attribute_name').eq('value of attribute you want to find')
)
items = response['Items']
print(items)
To ensure completeness, don't forget to include the import statement from boto3.dynamodb.conditions import Key, Attr
If you're interested in exploring the various methods and options available with the scan function, you can refer to the documentation provided here
Also, keep a note that
scan is relatively slower than query in comparison
Upvotes: 3
Reputation: 171
I've found what I was looking for:
I had to add the IndexName in my code like this.
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Testing-Table')
def lambda_handler(event, context):
response = table.query (
IndexName='status-index',
KeyConditionExpression=Key('status').eq('active')
)
for i in response['Items']:
print(i['user_id'],":",i['status'])
Here is an image of the result:
Upvotes: 10