问题
I am very beginner to AWS DynamoDB, I want to scan the DynamoDB with SENDTO.emailAddress = "first@first.com" as FilterExpression.
The DB Structure looks like this
{
ID
NAME
MESSAGE
SENDTO[
{
name
emailAddress
}
]
}
A Sample Data
{
ID: 1,
NAME: "HELLO",
MESSAGE: "HELLO WORLD!",
SENDTO: [
{
name: "First",
emailAddress: "first@first.com"
},
{
name: "Second",
emailAddress: "second@first.com"
}
]
}
I want to retrieve document that match emailAddress. I tried to scan with filter expression and here is my code to retrieve the data. I am using AWS Javascript SDK.
let params = {
TableName : "email",
FilterExpression: "SENDTO.emailAddress = :emailAddress",
ExpressionAttributeValues: {
":emailAddress": "first@first.com",
}
}
let result = await ctx.docClient.scan(params).promise();
回答1:
In order to find the item by sendto
attribute, you need to know both name
and emailAddress
attribute value. DynamoDB can't find the data by just one of the attributes in an object (i.e. email
attribute value alone).
CONTAINS function can be used to find the data in List data type.
CONTAINS is supported for lists: When evaluating "a CONTAINS b", "a" can be a list; however, "b" cannot be a set, a map, or a list.
Sample code using Contains:-
var params = {
TableName: "email",
FilterExpression: "contains (SENDTO, :sendToVal)",
ExpressionAttributeValues: {
":sendToVal": {
"name" : "First",
"emailAddress" : "first@first.com"
}
}
};
If you don't know the value of name
and emailAddress
attribute, you may need to remodel the data to fulfill your use case.
回答2:
I think that you should create two tables for users and for messages.
The user table has partition_key: user_id and sort_key: email and a field with an array of his messages ids.
The message table has partition_key: message_id and a field with an array of users ids.
When you will get the array of users ids you can use BATCH GET query to get all users of one message.
When you will get the array of message ids you can use BATCH GET query to get all messages of one user.
If you want to get one user by email you can use QUERY method.
Docs
来源:https://stackoverflow.com/questions/47294056/how-to-filter-nested-array-object-in-dynamodb