ensnare
ensnare

Reputation: 42013

Retrieve an item from a DynamoDB table that has a range key by only specifying the index key

I have a table with a primary key and range key set:

user_id
timestamp_joined

Using the boto api layer, is there a way I can retrieve the item just by specifying the user_id (without the range key)? Every time I perform a getItem() query without specifying the range key it fails. I can only get it to work by specifying the range key (timestamp_joined).

The error message when fetching just by user_id is below:

boto.exception.DynamoDBResponseError: DynamoDBResponseError: 400 Bad Request 
{'message': 'One or more parameter values were invalid: The provided 
key size does ot match with that of the schema', '__type':
'com.amazon.coral.validate#ValidationException'} 

Upvotes: 5

Views: 6772

Answers (3)

qarly_blue
qarly_blue

Reputation: 420

This works for me in date range

I have my table with dates: enter image description here

And I made a query like this:

import requests, json 
import boto3
from boto3.dynamodb.conditions import Key, Attr

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb', region_name='us-east-1', aws_access_key_id='your_access',aws_secret_access_key='your_secret')
    table = dynamodb.Table('Table_name')

    date_i = '2013-11-18'
    date_f = '2013-11-19'

    try:
        fe = Key('Date').between(date_i,date_f);
        response = table.scan(
            FilterExpression=fe
        )
        print(response['Items'])
    except Exception as e:
        print(e)
        raise e

I had 2 results with that range.

Upvotes: 0

WhiteRabbit
WhiteRabbit

Reputation: 109

result = table.scan(Attr('user_id').eq(/number here/),
                    Limit=1,
                    ConsistentRead=True)

If you have more than 1 item per user_id you can limit the results by a greater number up to 1M of results per scan or query.

Upvotes: 0

garnaat
garnaat

Reputation: 45846

It sounds like you want to perform a query. You can query the table specifying only the user_id (the hash key) and the query will return all items that match that user_id regardless of the range value.

Upvotes: 3

Related Questions