简体   繁体   中英

How can you query an item in a list field in DynamoDB using Python?

I have a table that contains an item with the following attributes:

{
  "country": "USA",
  "names": [
    "josh",
    "freddy"
  ],
  "phoneNumber": "123",
  "userID": 0
}

I'm trying to query an item in a DynameDB by looking for a name using python. So I would write in my code that the item I need has "freddy" in the field "names" .

I saw many forums mentioning "contains" but none that show an example...

My current code is the following:

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users_table')
data = table.query(
    FilterExpression: 'names = :name',
    ExpressionAttributeValues: {
      ":name": "freddy"
    }
)

I obviously cannot use that because "names" is a list and not a string field. How can I look for "freddy" in names ?

Since names field isn't part of the primary key, so you can't use query . The only way to look for an item by names is to use scan .

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

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users_table')
data = table.scan(
    FilterExpression=Attr('names').contains('freddy')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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