Updating list in dynamodb - amazon-dynamodb

How one can update a list in dynamodb. consider the following example
Section:"A",
Group:[{Name:"Albert",
Age:24},
{Name:"Antony",
Age:25}],
GroupName:"Ply"
Now I need to change Alberts age from 24 to 26, considering Section as my primary partition key
var params = {
TableName: "Add_list",
Key:{
Section:"A"
},
"UpdateExpression" : "#Key = :value",
"ConditionExpression":"#Key1 = :value1",
"ExpressionAttributeNames" : {
"#Key" : "Group",
"#Key1":"Group[0].Name"
},
"ExpressionAttributeValues" : {
":value" : [{Name:"Albert",Age:26}],
":value1" : "Albert"
}
};

Related

How I can reduce the time of a for loop in Flutter?

I have a method called getNearByPlaces(), then I have for loop that iterates over each place_id, and send a request to google API, to get the name of the place_id,
so this operation takes around 15 seconds, how I can make it faster?
Future<void> getNearByPlaces(double latitude, double longitude) async {
List results = [];
List placesId = [];
List nearbyPlaces = [];
String nearbyUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&key=${mapKey}";
var nearbyResponse =
await RequestAssistant.getRequest(Uri.parse(nearbyUrl));
if (nearbyResponse == "Failed.") {
return;
}
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
String placeDetailsUrl =
"https://maps.googleapis.com/maps/api/place/details/json?place_id=${results[i]['place_id']}&key=$mapKey";
var response =
await RequestAssistant.getRequest(Uri.parse(placeDetailsUrl));
if (response == "Failed.") {
return;
}
if (response["status"] == "OK") {
await nearbyPlaces.add(response["result"]["name"]);
}
}
print(nearbyPlaces);
await FirebaseFirestore.instance
.collection("nearbyPlaces")
.doc(uid)
.set({'nearbyPlaces': nearbyPlaces});
}
If you just use only name in the detail result, you don't need to query again by 'place_id' because I found that there are more information in 'nearbysearch' API results.
For example, icon, name, photos and so on like below.
https://developers.google.com/maps/documentation/places/web-service/search
{
"html_attributions" : [],
"next_page_token" : "CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q",
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.867217,
"lng" : 151.195939
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
"name" : "Biaggio Cafe - Pyrmont",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 600,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAmWmj0BqA0Jorm1_vjAvx1n6c7ZNBxyY-U9x99-oNyOxvMjDlo2npJzyIq7c3EK1YyoNXdMFDcRPzwLJtBzXAwCUFDGo_RtLRGBPJTA2CoerPdC5yvT2SjfDwH4bFf5MrznB0_YWa4Y2Qo7ABtAxgeBIQv46sGBwVNJQDI36Wd3PFYBoUTlVXa0wn-zRITjGp0zLEBh8oIBE",
"width" : 900
}
],
"place_id" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"price_level" : 1,
"rating" : 3.4,
"reference" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"types" : [ "cafe", "bar", "restaurant", "food", "establishment" ],
"vicinity" : "48 Pirrama Rd, Pyrmont"
},
So you just iterate 'nearbysearch' result and making 'nearbyPlaces' data.
...
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
nearbyPlaces.add(results[i]['name');
}
print(nearbyPlaces);
...

Is it possible to update existing Dynamo DB table from Terraform

I am trying to create a terraform module with the help of which I can make an entry to existing Dynamo DB table.
I have got this code which create dynamo DB table
resource "aws_dynamodb_table" "basic-dynamodb-table" {
name = "GameScores"
billing_mode = "PROVISIONED"
read_capacity = 20
write_capacity = 20
hash_key = "UserId"
range_key = "GameTitle"
attribute {
name = "UserId"
type = "S"
}
attribute {
name = "GameTitle"
type = "S"
}
attribute {
name = "TopScore"
type = "N"
}
ttl {
attribute_name = "TimeToExist"
enabled = false
}
global_secondary_index {
name = "GameTitleIndex"
hash_key = "GameTitle"
range_key = "TopScore"
write_capacity = 10
read_capacity = 10
projection_type = "INCLUDE"
non_key_attributes = ["UserId"]
}
tags = {
Name = "dynamodb-table-1"
Environment = "production"
}
}
Is there any way I can make changes in existing dynamo db table.
For adding entries to a table you can take a look at the aws_dynamodb_table_item resource. Here is an example that you can use to add an entry to your table:
resource "aws_dynamodb_table_item" "item1" {
table_name = aws_dynamodb_table.basic-dynamodb-table.name
hash_key = aws_dynamodb_table.basic-dynamodb-table.hash_key
range_key = aws_dynamodb_table.basic-dynamodb-table.range_key
item = <<ITEM
{
"UserId": {"S": "user"},
"GameTitle": {"S": "gamex"},
"TopScore": {"N": "42"}
}
ITEM
}

terraform nested dynamic block with nested map

I'm trying to get tf 0.12.x new dynamic feature to work with a nested map, config is below.
As you can see below (simplified for this) I'm defining all the variables and adding variable required_resource_access which contains a map.
I was hoping to use new dynamic feature to create read this map in a nested dyanmic block.
variable prefix {
description = "Prefix to applied to all top level resources"
default = "abx"
}
variable suffix {
description = "Suffix to applied to all valid top level resources, usually this is 2 letter region code such as we (westeurope), ne (northeurope)."
default = "we"
}
variable env {
description = "3 letter environment code appied to all top level resources"
default = "dev"
}
variable location {
description = "Where to create all resources in Azure"
default = "westeurope"
}
variable available_to_other_tenants {
default = false
}
variable oauth2_allow_implicit_flow {
default = true
}
variable public_client {
default = false
}
# other option is native
variable application_type {
default = "webapp/api"
}
variable required_resource_access {
type = list(object({
resource_app_id = string
resource_access = object({
id = string
type = string
})
}))
default = [{
resource_app_id = "00000003-0000-0000-c000-000000000000"
resource_access = {
id = "7ab1d382-f21e-4acd-a863-ba3e13f7da61"
type = "Role"
}
}]
}
variable reply_urls {
default = []
}
variable group_membership_claims {
default = "All"
}
resource "azuread_application" "bootstrap" {
name = "${var.prefix}-${var.env}-spn"
homepage = "http://${var.prefix}-${var.env}-spn"
identifier_uris = ["http://${var.prefix}-${var.env}-spn"]
reply_urls = var.reply_urls
available_to_other_tenants = var.available_to_other_tenants
oauth2_allow_implicit_flow = var.oauth2_allow_implicit_flow
type = var.application_type
group_membership_claims = var.group_membership_claims
dynamic "required_resource_access" {
for_each = var.required_resource_access
content {
resource_app_id = required_resource_access.value["resource_app_id"]
dynamic "resource_access" {
for_each = required_resource_access.value["resource_access"]
content {
id = resource_access.value["id"]
type = resource_access.value["type"]
}
}
}
}
}
But for reasons beyond my knowledge it keeps giving me this error (notice it's priting it twice as well), I've tried a few other options but this is the closest I managed to get where it would at least give me a meaningful error.
------------------------------------------------------------------------
Error: Invalid index
on pe_kubernetes.tf line 24, in resource "azuread_application" "bootstrap":
24: id = resource_access.value["id"]
|----------------
| resource_access.value is "7ab1d382-f21e-4acd-a863-ba3e13f7da61"
This value does not have any indices.
Error: Invalid index
on pe_kubernetes.tf line 24, in resource "azuread_application" "bootstrap":
24: id = resource_access.value["id"]
|----------------
| resource_access.value is "Role"
This value does not have any indices.
Error: Invalid index
on pe_kubernetes.tf line 25, in resource "azuread_application" "bootstrap":
25: type = resource_access.value["type"]
|----------------
| resource_access.value is "7ab1d382-f21e-4acd-a863-ba3e13f7da61"
This value does not have any indices.
Error: Invalid index
on pe_kubernetes.tf line 25, in resource "azuread_application" "bootstrap":
25: type = resource_access.value["type"]
|----------------
| resource_access.value is "Role"
This value does not have any indices.
Spent the best part of 2 days on this with no luck so any help or pointers would be much appreciated!
I had some time to test my comment...
If I change the resource_access to a list it works.
See code below:
variable required_resource_access {
type = list(object({
resource_app_id = string
resource_access = list(object({
id = string
type = string
}))
}))
default = [{
resource_app_id = "00000003-0000-0000-c000-000000000000"
resource_access = [{
id = "7ab1d382-f21e-4acd-a863-ba3e13f7da61"
type = "Role"
}]
}]
}
resource "azuread_application" "bootstrap" {
name = "test"
type = "webapp/api"
group_membership_claims = "All"
dynamic "required_resource_access" {
for_each = var.required_resource_access
content {
resource_app_id = required_resource_access.value["resource_app_id"]
dynamic "resource_access" {
for_each = required_resource_access.value["resource_access"]
content {
id = resource_access.value["id"]
type = resource_access.value["type"]
}
}
}
}
}
And the plan shows:
Terraform will perform the following actions:
# azuread_application.bootstrap will be created
+ resource "azuread_application" "bootstrap" {
+ application_id = (known after apply)
+ available_to_other_tenants = false
+ group_membership_claims = "All"
+ homepage = (known after apply)
+ id = (known after apply)
+ identifier_uris = (known after apply)
+ name = "test"
+ oauth2_allow_implicit_flow = true
+ object_id = (known after apply)
+ owners = (known after apply)
+ public_client = (known after apply)
+ reply_urls = (known after apply)
+ type = "webapp/api"
+ oauth2_permissions {
+ admin_consent_description = (known after apply)
...
}
+ required_resource_access {
+ resource_app_id = "00000003-0000-0000-c000-000000000000"
+ resource_access {
+ id = "7ab1d382-f21e-4acd-a863-ba3e13f7da61"
+ type = "Role"
}
}
}
Plan: 1 to add, 0 to change, 0 to destroy.
I removed a lot of your variables an some of the optional Arguments for azuread_application to keep the code as small as possible, but the same principle applies to your code, use lists on for_each or it will loop on the object properties.

Firebase realtime database multi location update through cloud function transactions not working

I got a firebase realtime db (js sdk) where I count users for each location (groups/location/Items/{locationId}/usercount). I also have at a root level, a list of users where for each user I have a list of locations. Within each of these locations I have a counter that counts the total number of useres for that location (users/{userId}/groups/location/Items/{locationId}/usercount).
a) So whenever a user is added to to a location at groups/location/Items/{locationId}/users, the counter at groups/location/Items/{locationId}/usercount is incremented.
b) At the same time a counter at users/groups/location/Items/{locationId}/usercount is also incremented for each user that has this location in users/{userId}/groups/location/Items/.
Below you'll find the json data structure as well as the cloud function supposed to increment both counters (a and b). Part (a) of the function works perfectly. As for part (b) it only works for the user that was just added at groups/location/Items/{locationId}/users (user yjXidCKJuYZ71TNzYe9ob5Raaub2 as per hereby json) on not for ALL users at users/{userId}.
I need this function to increment all the counters of users within users/{userId} that have the location to which a user was added.
I hope I'm clear enough and would REALLY appreciate some help on this. Maybe I should not be using transactions.
Thanks a lot!
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 2,
"users" : {
"Xi6XiXdxDAWqvjmSUeobnhDTe4k2" : {
"created" : "2019-04-03--19:10:11",
"id" : "Xi6XiXdxDAWqvjmSUeobnhDTe4k2",
"ip" : "hidden",
"label" : "Anonymous"
},
"yjXidCKJuYZ71TNzYe9ob5Raaub2" : {
"created" : "2019-04-03--19:10:11",
"id" : "yjXidCKJuYZ71TNzYe9ob5Raaub2",
"ip" : "hidden",
"label" : "Anonymous"
}
}
}
}
}
},
"users" : {
"Xi6XiXdxDAWqvjmSUeobnhDTe4k2" : {
"created" : "2019-04-03--19:10:11",
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 1
}
}
}
},
"id" : "Xi6XiXdxDAWqvjmSUeobnhDTe4k2",
"ip" : "hidden",
"label" : "Anonymous"
},
"yjXidCKJuYZ71TNzYe9ob5Raaub2" : {
"created" : "2019-04-03--19:10:11",
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 2
}
}
}
},
"id" : "yjXidCKJuYZ71TNzYe9ob5Raaub2",
"ip" : "hidden",
"label" : "Anonymous"
}
}
}
exports.onUserAddToLocation = functions.database
.ref('/groups/location/Items/{itemId}/users/{userId}')
.onCreate((snapshot, context) => {
const itemId = context.params.itemId
const userId = context.params.userId
const groupCounterRef = admin.database().ref('/groups/location/Items/' + itemId + '/usercount');
return groupCounterRef.transaction(usercount => {
return (usercount || 0) + 1
}).then(result => {
const count = result.snapshot.val();
const userGroupsCounterRef = admin.database().ref('/users/' + userId + '/groups/location/Items/' + itemId + '/usercount');
userGroupsCounterRef.transaction(usercount => {
return count
})
})
})
This does the trick :
.ref('/groups/location/Items/{itemId}/users/{userId}')
.onCreate((snapshot, context) => {
const itemId = context.params.itemId
const groupCounterRef = admin.database().ref('/groups/location/Items/' + itemId + '/usercount');
return groupCounterRef.transaction(usercount => {
return (usercount || 0) + 1
}).then(result => {
const count = result.snapshot.val();
const usersRef = admin.database().ref("users").orderByKey();
usersRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot){
const userId = childSnapshot.key
const userLocationCountersRef = admin.database().ref('users/' + userId + '/groups/location/Items/' + itemId)
const hasThisGroup = childSnapshot.hasChild('/groups/location/Items/' + itemId)
if(hasThisGroup){
userLocationCountersRef.update({usercount:count})
}
})
})
})
})
This increments a counter for each user added to a location. After transaction success it copies that counter value to each user that has this location.

Realm. Get subset of inner element based on outer one

There is a structure:
{ "groups": [
{ "gid" : 1,
"elements" : [
{ "eid" : 1 },
{ "eid" : 2 }
]
},
{ "gid" : 2,
"elements" : [
{ "eid" : 11 },
{ "eid" : 22 }
]
}
{ "gid" : 3,
"elements" : [
{ "eid" : 21 },
{ "eid" : 32 }
]
}
]
}
I understand how to get all groups:
RealmResults<Group> all = realm.where(Group.class).findAll();
Also I could get all elements or all elements in a group.
But how could I query all element from groups that have id > 1?
RealmResults<Group> allFilteredGroups = realm.where(Group.class).greaterThan("gid", 1).findAll();
Is it possible to retrive all elements from all allFilteredGroups by one query, smth like
realm.where(Element.class).equalsTo(???, allFilteredGroups).findall() ?
I'm not quite sure what you mean by "to retrieve all elements". allFilteredGroups has all the Group objects. As they are linked to the Elements objects, you can easily iterate through them:
for(Group group : allFilteredGroups) {
for(Element element : group.getElement()) {
Log.d("TEST", "eid = " + element.eid);
}
}
There is currently no easy way to flatten the last and have all the Element objects in a single RealmResults.

Resources