简体   繁体   English

如何使用 Python 在 DynamoDB 的列表字段中查询项目?

[英]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.我正在尝试通过使用 python 查找名称来查询 DynameDB 中的项目。 So I would write in my code that the item I need has "freddy" in the field "names" .所以我会在我的代码中写下我需要的项目在"names"字段中有"freddy" ”。

I saw many forums mentioning "contains" but none that show an example...我看到很多论坛提到"contains" ,但没有一个显示示例......

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.我显然不能使用它,因为"names"是一个列表,而不是一个字符串字段。 How can I look for "freddy" in names ?如何在names中查找"freddy"

Since names field isn't part of the primary key, so you can't use query .由于names字段不是主键的一部分,因此您不能使用query The only way to look for an item by names is to use scan .names查找项目的唯一方法是使用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')
)

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

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