[英]Query GSI in DynamoDb with a substring of the key (begins_with)
Let's take the best practices for sort keys official documentation of DynamoDb as an example: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-sort-keys.html下面以DynamoDb官方文档sort keys的最佳实践为例: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-sort-keys.html
Imagine we have a table like the documentation mentions, where our sort key is a composite that looks like:想象一下,我们有一个像文档中提到的表,其中我们的排序键是一个组合,如下所示:
[country]#[region]#[city]#[neighborhood]
For example, something like this:例如,像这样:
Partition Key (Employee Name)![]() |
Sort Key![]() |
Other columns...![]() |
---|---|---|
Antonio![]() |
Spain#Madrid#Getafe#Whatever![]() |
... ![]() |
Maria![]() |
Spain#Andalucia#Sevilla#Whatever2![]() |
... ![]() |
Mike![]() |
Spain#Madrid#Alcorcon#Whatever![]() |
... ![]() |
And I'd like to get all the records from a specific country + region, so we have a partial sort key:我想获取特定国家/地区的所有记录,因此我们有一个部分排序键:
[country]#[region]
like Spain#Madrid
to get Antonio
and Mike
. [country]#[region]
像Spain#Madrid
一样得到Antonio
和Mike
。
I know it's not possible to query by sort key directly, so I created a GSI with the inverted index (like mentioned here https://stackoverflow.com/a/64141405 )我知道不可能直接通过排序键查询,所以我创建了一个带有倒排索引的 GSI(就像这里提到的https://stackoverflow.com/a/64141405 )
Partition Key![]() |
Sort Key![]() |
Other columns...![]() |
---|---|---|
Spain#Madrid#Getafe#Whatever![]() |
Antonio![]() |
... ![]() |
Spain#Andalucia#Sevilla#Whatever2![]() |
Maria![]() |
... ![]() |
Spain#Madrid#Alcorcon#Whatever![]() |
Mike![]() |
... ![]() |
But it still looks like it's not possible to query using the begins_with
operator.但看起来仍然无法使用
begins_with
运算符进行查询。
var request = new QueryRequest
{
IndexName = "GSI_Name",
KeyConditionExpression = "begins_with(SortKey, :v_SortKey)",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{":v_SortKey", new AttributeValue { S = sortKey }},
},
};
My question is: is there any way to achieve this without using the Scan
operation which is not ideal?我的问题是:有没有办法在不使用不理想的
Scan
操作的情况下实现这一目标? Or any suggestion to change my table definition to achieve this?或任何更改我的表定义以实现此目的的建议? I've been trying to think of ways of restructuring the table to accomplish this behavior, but I'm not fluent enough with DynamoDB.
我一直在想办法重组表以完成此行为,但我对 DynamoDB 不够流利。
Use the country as the PK and the rest as the SK.使用国家作为 PK,rest 作为 SK。 That spreads the data nicely across partitions while also enabling your access pattern.
这可以很好地跨分区分布数据,同时还支持您的访问模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.