gpt4 book ai didi

ruby - 通过哈希和范围键查询 DynamoDB 表

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:23 24 4
gpt4 key购买 nike

我想使用适用于 Ruby V2 的 AWS 开发工具包通过哈希和范围键查询 DynamoDB 表。以下代码可以工作。

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
table_name: TABLE_NAME,
key_conditions: {
HASH_KEY_NAME => {
attribute_value_list: ['hoge'],
comparison_operator: 'EQ'
},
RANGE_KEY_NAME => {
attribute_value_list: ['foo'],
comparison_operator: 'EQ'
}
}
)

但是,我想将多个项目设置为范围关键条件。

像这样:

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
table_name: TABLE_NAME,
key_conditions: {
HASH_KEY_NAME => {
attribute_value_list: ['hoge'],
comparison_operator: 'EQ'
},
RANGE_KEY_NAME => {
attribute_value_list: ['foo', 'bar'],
comparison_operator: 'EQ'
}
}
)

此代码返回 lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call':一个或多个参数值无效:EQ ComparisonOperator (Aws::DynamoDB::Errors::ValidationException) 的参数数量无效

我试过使用 IN 运算符。

dynamodb = Aws::DynamoDB::Client.new(region: 'somewhere')
dynamodb.query(
table_name: TABLE_NAME,
key_conditions: {
HASH_KEY_NAME => {
attribute_value_list: ['hoge'],
comparison_operator: 'EQ'
},
RANGE_KEY_NAME => {
attribute_value_list: ['foo', 'bar'],
comparison_operator: 'IN'
}
}
)

它返回 lib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call': Attempted条件约束不是可索引操作(Aws::DynamoDB::Errors::ValidationException)

如何通过一个哈希键和多个范围键查询 DynamoDB 表?

最佳答案

Query 操作仅允许在 Range Key 上使用以下运算符:

EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN

For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions, only the following comparison operators are supported:

EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN

Source: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html

您仍然可以通过使用 FilterExpression 来满足要求:

:filter_expression => "RANGE_KEY_NAME in (:id1, :id2)",{ ":id1" => "hoge",":id2" => "foo"}

但是,消耗的配置吞吐量将基于查询返回的结果而不是过滤的结果集。

另一种选择是通过 BatchGetItem 发送多个 GetItem 请求(每个请求都有一个可能的 Range Key 值)。结果将只包含匹配的记录:

resp = dynamodb.batch_get_item(
# required
request_items: {
"TableName" => {
# required
keys: [
{
"AttributeName" => "value", #<Hash,Array,String,Numeric,Boolean,nil,IO,Set>,
},
],
attributes_to_get: ["AttributeName", '...'],
consistent_read: true,
projection_expression: "ProjectionExpression",
expression_attribute_names: { "ExpressionAttributeNameVariable" => "AttributeName" },
},
},
return_consumed_capacity: "INDEXES|TOTAL|NONE",
)

来源:http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html

关于ruby - 通过哈希和范围键查询 DynamoDB 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30735226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com