I am currently developing a skill for Amazon's echo dot which requires the use of persistent data. I ran into an issue when developing a web interface for my skill where I was not able to easily update the mapAttr column of the DynamoDB table used by the skill.
I've been trying to work this out for the last 2 days, I've looked everywhere including the documentation but can't seem to find anything that'll help me.
This is the code I am using:
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#attr' => 'mapAttr.ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => json_encode($value)
],
'UpdateExpression' => 'SET #attr = :val1'
]);
I have tried many different things so this might be just absolutely wrong, but nothing that I have found has worked.
The table has 2 columns, userId and mapAttr, userId is a string and mapAttr is a map. Originally I thought it was simply a JSON string but it was not like that as when I tried to update it with a JSON string directly it would stop working when read by Alexa.
I am only trying to update 1 out of the 2 attributes of mapAttr. That is ReminderJSON which is a string.
Any help would be appreciated. Thanks.
Try calling updateItem like this
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr',
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
]);
However, please be aware that in order for this to work, attribute mapAttr must already exist. If it doesn't, you'll get ValidationException saying The document path provided in the update expression is invalid for update...
As a workaround, you may want to add a ConditionExpression => 'attribute_exists(mapAttr)' to your params, catch possible exception, and then perform another update adding a new attribute mapAttr:
try {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
'#attr' => 'ReminderJSON'
],
'ExpressionAttributeValues' => [
':val1' => ['S' => json_encode($value)]
],
'UpdateExpression' => 'SET #mapAttr.#attr = :val1'
'ConditionExpression' => 'attribute_exists(#mapAttr)'
]);
} catch (\Aws\Exception\AwsException $e) {
if ($e->getAwsErrorCode() == "ConditionalCheckFailedException") {
$result = $client->updateItem([
'TableName' => 'rememberThisDBNemo',
'Key' => [
'userId' => [ 'S' => $_SESSION['userDataAsk'] ]
],
'ExpressionAttributeNames' => [
'#mapAttr' => 'mapAttr'
],
'ExpressionAttributeValues' => [
':mapValue' => ['M' => ['ReminderJSON' => ['S' => json_encode($value)]]]
],
'UpdateExpression' => 'SET #mapAttr = :mapValue'
'ConditionExpression' => 'attribute_not_exists(#mapAttr)'
]);
}
}
Related
Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,
Hi so I'm trying to save data through Cakephp3 framework. I have two tables Measures and MeasuresUsers. Measures has many MeasuresUsers
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id']
];
$measure = $this->Measures->newEntity($data,['associated' => ['MeasuresUsers']]);
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
$this->Measures->save($measure)
I'm able to save data into Measures table but not into the associative table (MeasuresUsers). I'm not sure what I'm missing here, any help or comments is appreciated!
#HarryM. is close, but you want to put your data into the $data array before creating the entity (the associated tag is kinda pointless if you're not providing that data!), and since it's a hasMany relation, I think you need to have the data in an array of arrays:
$data = [
'name' => $this->request->data['name'],
'description' => $this->request->data['description'],
'deleted' => $this->request->data['deleted'],
'chart_type' => $this->request->data['chart_type'],
'public' => $this->request->data['public'],
'user_id' => $this->request->data['user_id'],
'measures_users' => [
[
'user_id' => $user['id'], // Should this be $this->request->data['user_id'] instead?
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public'],
],
],
];
$measure = $this->Measures->newEntity($data, ['associated' => ['MeasuresUsers']]);
$this->Measures->save($measure);
Coming from CakePHP 2.x, I see your associate model is MeasuresUsers.
When you're setting the associated data in
$measure['measures_users'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
Trying changing $measure['measures_users'] to $measure['MeasuresUsers']:
$measure['MeasuresUsers'] = [
'user_id' => $user['id'],
'chart_type' => $this->request->data['chart_type'],
'deleted' => $this->request->data['deleted'],
'public' => $this->request->data['public']
];
CakePHP's model conventions usually assume camel casing of what you have in the database e.g. DB Table it movie_tickets and Cake would expect is as MovieTicket unless otherwise declared in the Model itself.
I have the structure below which I need to turn into json_encoded. To finally get it decoded and get an object.
This will allow me to have multiple objects with the name message and loop through them and process each message individually.
However when encoded, php will only encode the key and one of the message arrays—the last one.
$setup = [
'key' => 'demo-7hn3fh83un3yhvfjvnjgknfhjnvf',
'message' => [
'number' => [
'+39XXXXXXXX',
'+34XXXXXXXX',
'+49XXXXXXXX'
],
'text' => 'Sample msg 123...',
],
'message' => [
'number' => [
'+50XXXXXXXX',
'+50XXXXXXXX'
],
'text' => 'Something...',
]
];
Is there a way to encode multiple arrays with the same name?
You've overlooked the root issue:
$foo = [
'bar' => 1,
'bar' => 2,
'bar' => 3,
];
var_export($foo);
array (
'bar' => 3,
)
Thanks for the tips everyone. I ended up modifying the structure like below...
The reason why I am going with a structure like this is cause it allows me to submit multiple messages to multiple users with a single request.
$setup = [
'key' => 'demo-7hn3fh83un3yhvfjvnjgknfhjnvf',
'message' => [
[
'number' => [
'+39XXXXXXXX',
'+34XXXXXXXX',
'+49XXXXXXXX'
],
'text' => 'Sample msg 123...'
],
[
'number' => [
'+50XXXXXXXX',
'+50XXXXXXXX'
],
'text' => 'Something...'
]
]
];
I am using php's client library for elasticsearch. I'd like to create an index that indexes a person's id and his name, and allows the user to search for names in a very flexible way (case insensitive, search for partial names, etc.
Here is a code snippet of what I have so far, annotated with comments for convenience
<?php
require_once(__DIR__ . '/../init.php');
$client = new Elasticsearch\Client();
$params = [
'index' => 'person',
'body' => [
'settings' => [
// Simple setings for now, single shard
'number_of_shards' => 1,
'number_of_replicas' => 0,
'analysis' => [
'filter' => [
'shingle' => [
'type' => 'shingle'
]
],
'analyzer' => [
'my_ngram_analyzer' => [
'tokenizer' => 'my_ngram_tokenizer',
]
],
// Allow searching for partial names with nGram
'tokenizer' => [
'my_ngram_tokenizer' => [
'type' => 'nGram',
'min_gram' => 1,
'max_gram' => 15,
'token_chars' => ['letter', 'digit']
]
]
]
],
'mappings' => [
'_default_' => [
'properties' => [
'person_id' => [
'type' => 'string',
'index' => 'not_analyzed',
],
// The name of the person
'value' => [
'type' => 'string',
'analyzer' => 'my_ngram_analyzer',
'term_vector' => 'yes',
'copy_to' => 'combined'
],
]
],
]
]
];
// Create index `person` with ngram indexing
$client->indices()->create($params);
// Index a single person using this indexing scheme
$params = array();
$params['body'] = array('person_id' => '1234', 'value' => 'Johnny Appleseed');
$params['index'] = 'person';
$params['type'] = 'type';
$params['id'] = 'id';
$ret = $client->index($params);
// Get that document (to prove it's in there)
$getParams = array();
$getParams['index'] = 'person';
$getParams['type'] = 'type';
$getParams['id'] = 'id';
$retDoc = $client->get($getParams);
print_r($retDoc); // success
// Search for that document
$searchParams['index'] = 'person';
$searchParams['type'] = 'type';
$searchParams['body']['query']['match']['value'] = 'J';
$queryResponse = $client->search($searchParams);
print_r($queryResponse); // FAILURE
// blow away index so that we can run the script again immediately
$deleteParams = array();
$deleteParams['index'] = 'person';
$retDelete = $client->indices()->delete($deleteParams);
I have had this search feature working at times, but I've been fussing with the script to get the case insensitive feature working as expected, and in the process, the script now fails to find any person with a J or j used as the query value to match.
Any ideas what might be going on here?
To fix the case insensitive bit, I added
'filter' => 'lowercase',
to my ngram analyzer.
Also, the reason why it was failing to begin with is that, while using php's client library, you can't create the index then search it in the same script. My guess is something async is going on here. So create the index in one script and search it in another script, it should work.
I'm having trouble duplicating my MySQL delete query in elastic search, I am using this documentation: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html using the PHP wrapper for Laravel.
I'm trying this:
$this->es->deleteByQuery([
'index' => 'users',
'type' => 'user',
'body' => [
'query' => [
'term' => ['field1' => $this->field1],
'term' => ['field2' => $this->field2],
'term' => ['temp' => 0]
]
]
]);
Its suppose to be a DELETE FROM users WHERE field1 = $this->field1 AND field2 = $this->field2...
I'm having trouble translating the WHERE AND syntax to Elastic Search.
Any help?
Your second comment was mostly correct:
I think I have have gone overboard right now. I have body => query =>
filter => filtered => bool => must => term, term, term. Do I need the
filter => filtered arrays?
The bool filter is preferable over the bool query, since filtering is often much faster than querying. In your case, you are simply filtering documents that have the various terms, and don't want them contributing to the score, so filtering is the correct approach.
This should be done though the query clause, however, since the top-level filter clause is used for a different purpose (filtering facets/aggregations...it was in-fact renamed to post_filter in 1.0 to signify that it is a "post filtering" operation).
Your query should look something like this:
$this->es->deleteByQuery([
'index' => 'users',
'type' => 'user',
'body' => [
'query' => [
'filtered' => [
'filter' => [
'must' => [
['term' => ['field1' => $this->field1]],
['term' => ['field2' => $this->field2]],
['term' => ['temp' => 0]]
]
]
]
]
]
]);