c# - 如何在 DynamoDB 中使用 c# 在排序键上使用 begin_with 方法
问题描述
如果我要使用高级模型,我可能会尝试这样的事情:
public async void GetBooksData()
{
GetItemRequest request = new GetItemRequest
{
TableName = "Customer",
Key = new Dictionary<string, AttributeValue>
{
{"UserName", new AttributeValue{S="a"} },
{"BookNum", new AttributeValue { S = starts_with(queryTerm)} }
}
};
try
{
var response = await client.GetItemAsync(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
if (response.Item.Count > 0)
{
foreach (var item in response.Item)
{
MessageBox.Show("Value : \n" + item.Value.S);
}
}
}
}
catch (InternalServerErrorException iee)
{
MessageBox.Show(iee);
}
}
我需要使用方法“begins_with”来获取用户名是“a”的 2 个项目,而 BookNum 是 book_1 和 book_2。这在 Java 的高级接口中是可能的。作为一个例子,可以对 Java 中的范围键执行什么操作:
public List<Comment> allForItemWithMinRating(String itemId, int minRating) {
Comment comment = new Comment();
comment.setItemId(itemId);
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.GE)
.withAttributeValueList(
new AttributeValue()
.withN(Integer.toString(minRating)));
DynamoDBQueryExpression<Comment> queryExpression
= new DynamoDBQueryExpression<Comment>()
.withHashKeyValues(comment)
.withRangeKeyCondition(
"rating",
condition
)
.withScanIndexForward(false);
return mapper.query(Comment.class, queryExpression);
}
在 C# 的低级接口中,您可以这样实现:
var requestDynamodb = new QueryRequest
{
TableName = "GroupEdEntries",
KeyConditionExpression = "partition_key = :s_Id and begins_with(sort_key, :sort)",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{":s_Id", new AttributeValue { S = my_id }},
{":sort", new AttributeValue { S = sort_key_starts_with }}
},
ConsistentRead = true
};
var results = await client.QueryAsync(requestDynamodb);
键被调用的地方partition_key
和sort_key
。但是,这会将结果作为属性值返回,然后需要一次将其转换为 POCO 一个属性。它需要使用反射并且使用转换器变得更加复杂。C# SDK 不支持此基本功能(以及其他功能)似乎很奇怪。我最终使用反射来创建基于属性的表,而 Java 默认也支持这一点。我是否缺少 C# 的高级 API?
解决方案
这是一种不同的语法,我在任何地方都找不到它的文档(除了在代码注释中),但这对我有用:
string partition_key = "123";
string sort_key_starts_with = "#type"
List<object> queryVal = new List<object>();
queryVal.Add(sort_key_starts_with);
var myQuery = context.QueryAsync<GroupEdEntry>(partition_key, QueryOperator.BeginsWith, queryVal);
var queryResult = await myQuery.GetRemainingAsync();
推荐阅读
- swift - 我怎样才能成功使用委托?按钮不适用于代表
- python - ImportError:无法导入名称'deprecated_endpoints'?
- html - 如何使用 SVG 路径从地图中获取坐标?
- java - 为什么我从 flink 得到重复的数据?
- python - 找到一个值的子集的最佳近似值
- ruby-on-rails - Rails 仅在应用程序启动时运行一次作业
- reactjs - 字段组件中的 reduxForm 验证问题(错误:超出最大更新深度)
- android - 如何让本地化字体在运行时工作?
- python - 如何使用 Python 代码在一个绘图上叠加两个多项式回归图?
- wordpress - 将主网站网址从 http 更改为 https