简体   繁体   English

使用密钥的 substring (begins_with) 在 DynamoDb 中查询 GSI

[英]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西班牙#安达卢西亚#塞维利亚#Whatever2 ... ...
Mike麦克风 Spain#Madrid#Alcorcon#Whatever西班牙#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一样得到AntonioMike

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西班牙#安达卢西亚#塞维利亚#Whatever2 Maria玛丽亚 ... ...
Spain#Madrid#Alcorcon#Whatever西班牙#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.

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