通过哈希和范围键查询 DynamoDB table

Querying DynamoDB table by hash and range key

我想通过哈希和范围键查询 DynamoDB table,使用适用于 Ruby V2 的 AWS SDK。以下代码可以工作。

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'
    }
  }
)

此代码returnslib/ruby/gems/2.2.0/gems/aws-sdk-core-2.0.48/lib/seahorse/client/plugins/raise_response_errors.rb:15:in `call': One or more parameter values were invalid: Invalid number of argument(s) for the 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'
    }
  }
)

它returns 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 conditional constraint is not an indexable operation (Aws::DynamoDB::Errors::ValidationException).

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

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