0

Getting Below Error:

{
  "errorMessage": "name 'Emp_id' is not defined",
  "errorType": "NameError",
  "requestId": "4b66e8ca-28f8-4005-8589-3993d2d4d203",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 12, in lambda_handler\n    hash_key=Emp_id, ScanIndexForward=True, limit=1\n"
  ]
}
import json
import boto3
from boto3.dynamodb.conditions import Key


def lambda_handler(event, context):
 ddb = boto3.resource('dynamodb', region_name='ap-south-1')

 table = ddb.Table('newtable2')

 response = table.query (
        hash_key=Emp_id, ScanIndexForward=True, limit=1
        )
 print(response['Items'])   
jellycsc
  • 10,904
  • 2
  • 15
  • 32
  • Please check the syntax of the query-API. You're using the `Emp_id` variable that's not defined in your code. Additionally, the parameter for the `query` call is not called `hash_key`. Here are the docs: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Table.query – Maurice Jan 12 '23 at 18:33
  • 1
    @JonSG OP's problem is only vaguely related to the duplicate, I believe they already know how the query is supposed to be working, the Python implementation is the problem. – Maurice Jan 12 '23 at 18:34

1 Answers1

1

You're already on the right track with the implementation, but there are a few problems:

  • You're referring to Emp_id which is not defined anywhere, thus the NameError
  • You're using the hash_key parameter which doesn't exist in the query-api

This is roughly what your code needs to look like:

import json
import boto3
from boto3.dynamodb.conditions import Key


def lambda_handler(event, context):
    ddb = boto3.resource('dynamodb', region_name='ap-south-1')

    table = ddb.Table('newtable2')

    response = table.query (
        KeyConditionExpression=Key("<name-of-partition-key>").eq("<value-of-partition-key>"),
        ScanIndexForward=True,
        Limit=1
    )
    print(response['Items'])  

You'd replace <name-of-partition-key> with the name of the partition key as defined in your DynamoDB table. <value-of-partition-key> needs to be replaced with the attribute you're looking for. In your case, presumably some sort of Employee ID.

The question that was mentioned as a potential duplicate target explains the rationale for the ScanIndexForward and Limit parameter values but uses a syntax that's not consistent with boto3.

Maurice
  • 11,482
  • 2
  • 25
  • 45