0

I am new to Dynamodb and learning currently. I am using python to query dynamodb to get some records based on a IF condition.

I have a dynamodb table cus_token, has only two attributes a) customerId and b) token

Token Table

When a user provides token, check if that token exists in the cus_token table, and if it exists I want to query out and fetch the customerID for that token. I tried to to do it this way

Suppose user_input = "Rooxp9" (this is a token in the cus_token table)

first get all the values with token attribute

import boto3
import json

def gettokens(y):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('cus_token')
    response = table.scan()

    tokens = []
    for i in response['Items']:
        nameList.append(i['token'])

    return tokens

temp = gettokens(cus_token)

Check using IF condition

for item in temp:
    if item == user_input:
        "Here I want to write the code to fetch the customerID"

1 Answer 1

1

It sounds like you'd like to fetch a customerID given a token.

To do this with your current table design, you'd want to use a Filter Expression to ask DynamoDB to return all attributes where the token is equal to the user input. For example, here's a snippet in pseudocode:

response = table.scan({"FilterExpression": "#token = :token",
                       "ExpressionAttributeNames": {"#token":"token"},
                       "ExpressionAttributeValues": {":token": {"S": <user_input>}})

There's no need to scan the entire database, return it to your application, then filter the results in your application.

If you are just getting started with DynamoDB, I'd highly recommend The DynamoDB Guide website. It does a great job explaining DynamoDB to beginners.

Sign up to request clarification or add additional context in comments.

2 Comments

I also want to validate whether user given token matches with the token existing the in table. Only If the token matches, I need to fetch the corresponding customerID
This scan operation will only return items where the token matches what you ask for (the user input). If there is no match, you will get no results. There is no need for additional validation. By default, the scan operation will return all attributes in the matching items, meaning you will have the CustomerID in your results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.