简体   繁体   English

使用 python 检查 dynamodb 表中是否存在值并获取该记录

[英]check if a value exists in dynamodb table using python and fetch that record

I am new to Dynamodb and learning currently.我是 Dynamodb 的新手,目前正在学习。 I am using python to query dynamodb to get some records based on a IF condition.我正在使用 python 查询 dynamodb 以根据 IF 条件获取一些记录。

I have a dynamodb table cus_token , has only two attributes a) customerId and b) token我有一个 dynamodb 表cus_token ,只有两个属性 a) customerId 和 b) token

令牌表

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.当用户提供令牌时,检查该令牌是否存在于 cus_token 表中,如果存在,我想查询并获取该令牌的 customerID。 I tried to to do it this way我试着这样做

Suppose user_input = "Rooxp9" (this is a token in the cus_token table)假设user_input = "Rooxp9" (这是 cus_token 表中的一个 token)

first get all the values with token attribute首先获取所有具有 token 属性的值

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使用 IF 条件检查

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

It sounds like you'd like to fetch a customerID given a token .听起来您想在给定token的情况下获取customerID

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.要在当前的表设计中执行此操作,您需要使用过滤器表达式来要求 DynamoDB 返回token等于用户输入的所有属性。 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 .如果您刚刚开始使用 DynamoDB,我强烈推荐DynamoDB 指南网站 It does a great job explaining DynamoDB to beginners.它很好地向初学者解释了 DynamoDB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM