Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query all rows of one column in DynamoDB?

I just work with AWS DynamoDB in a short of time. I am wondering how can I get the same result with this statement (without WHERE clause):

SELECT column1 FROM DynamoTable;

I tried (but failed) with:

 import boto3
 dynamodb = boto3.resource('dynamodb')
 table = dynamodb.Table('DynamoTable')
 from boto3.dynamodb.conditions import Key, Attr
 resp = table.query(KeyConditionExpression=Key('column1'))

It requires Key().eq() or Key().begin_with() ...

I tried with resp = table.scan() already, but the response data is too many fields while I only need column1

Thanks.

like image 872
Lê Tư Thành Avatar asked Dec 03 '22 18:12

Lê Tư Thành


2 Answers

This lets you get the required column directly and you do not need to iterate over the whole dataset

import boto3

def getColumn1Items():
     dynamodb = boto3.resource('dynamodb')
     table = dynamodb.Table('DynamoTable')
     resp = table.scan(AttributesToGet=['column1'])

     return resp['Items']
like image 156
ampersand Avatar answered Dec 28 '22 06:12

ampersand


You should definitely use Scan operation. Check the documentation to implement it with python.

Regarding how to select just a specific attribute you could use:

import boto3

def getColumn1Items():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('DynamoTable')
    response = table.scan()

    return [i['column1'] for i in response['Items']]

You have to iterate over the the entire table and just fetch the column you need.

like image 21
ALFA Avatar answered Dec 28 '22 06:12

ALFA