I have 2 problems. I want to query a dynamodb database on Bool and on Date.
Is this possible as I only see String Number and Binary?
There are two types of expressions.
KeyConditionExpression - Supports only String, Number and Binary
FilterExpression - Can be used for Non-Key attributes. You can query for the Date and BOOL attributes.
There is a BETWEEN operator which can be used for DATE range as well.
Code to filter by Date:-
var params = {
TableName : table,
KeyConditionExpression : 'email = :email',
FilterExpression: 'createdAt = :createdAt',
ExpressionAttributeValues : {
':email' : 'abc#gmail.com',
':createdAt' : "2016-11-07"
}
};
My Item:-
Date is stored as String in database.
Date S (string type). The Date values are stored as ISO-8601 formatted
strings.
Related
I have received the following string:
{"records":[{"id":"rec4haaOncoQniu8U","fields":{"orders1":5},"createdTime":"2020-02-08T09:08:22.000Z"}]}
I am not understanding how I can process and separate the values of the json in mql4 using the "JAson.mqh " library, located here: https://www.mql5.com/en/code/13663
I need the values of "orders" located under "fields" , value = 5.
the only "KEYS" that changes are the keys within the "fields" values.
i would like to be able to get the values with something like this:
string value1 = Result[0].["fields"].["orders1"]; //5
string value2 = Result[0].["fields"].["orders2"];
Please let me know what I can do.
You can get the value using the following format. Note that it has to be casted to a type. (I have casted it to int as it is the type it is in the JSON, but you can cast it to string as well)
int value1 = json["records"][0]["fields"]["orders1"].ToInt(); // if you want to make it a string use ToStr() instead of ToInt()
Here is a full example of what I did
string jsonString = "{\"records\": [{\"id\": \"rec4haaOncoQniu8U\",\"fields\": {\"orders1\": 5 }\"createdTime\": \"2020-02-08T09:08:22.000Z\"}]}";
if(json.Deserialize(jsonString))
Alert(json["records"][0]["fields"]["orders1"].ToInt());
Hope it helped.
How do I filter a dynamoDB table with an expression on a bool value. I can filter successfully on an Int or String value. But even in the web console when trying to create a filter expression on a bool value it won't give any results back?
I'm trying this from Swift on iOS as well, but the fact that it doesn't even work int he web interface makes me wonder how to at all achieve this.
If I filter on an Int it works, i.e.
let queryExpression = AWSDynamoDBQueryExpression()
queryExpression.rangeKeyConditionExpression = "age = :val"
queryExpression.expressionAttributeValues = [":val": 30]
But if I try on an Bool it comes back with nothing.
let queryExpression = AWSDynamoDBQueryExpression()
queryExpression.rangeKeyConditionExpression = "enabled = :val"
queryExpression.expressionAttributeValues = [":val": true]
I've also tried a 0 or a 1 in place of true, or a string as in "true".
However, this filtering on an Bool doesn't even work in the AWS web interface. So it's not a Swift thing it seems. Maybe it's not possible, but seems odd.
Turns out I was confused here, filterExpression works fine.
let scanExpression = AWSDynamoDBScanExpression()
scanExpression.filterExpression = "disabled = :val"
scanExpression.expressionAttributeValues = [":val": false]
The documentation isn't very clear about this, but it is not possible to create a table in DynamoDB with a boolean hash or range key. The hash and range keys can only be of types string (S), numeric (N), or binary (B). If you try to create a table with a boolean (BOOL) range key such as:
create_table(
AttributeDefinitions=[
{'AttributeName': 'something', 'AttributeType': 'S'},
{'AttributeName': 'enabled', 'AttributeType': 'BOOL'}
],
TableName='example',
KeySchema=[
{'AttributeName': 'something', 'KeyType': 'HASH'},
{'AttributeName': 'enabled', 'KeyType': 'RANGE'},
]
...
)
the call will fail on the requirement that the 'enabled' range key be of type 'S', 'N' or 'B'.
If you want to effectively store a boolean in the range key, you should use the numeric type and assign 0 and 1 values, which can be filtered as you've already demonstrated.
If you have a boolean value that is not a hash or range key, you can filter it with a FilterExpression instead of a RangeKeyConditionExpression as described in the FilterExpression documentation.
The format of "new DateTime.now()" will print following output:
2015-05-20 07:34:43.018
By having only the time as a String in the correct format ("07:34:43.018"), how do I parse the time to a DateTime object? The usage of the intl package does not support the mentioned format AFAIK.
By prefixing the Date in front of the time, DateTime would be able to parse the given String.
DateTime parse(String timeValue) {
var prefix = '0000-01-01T';
return DateTime.parse(prefix + timeValue);
}
If you also only want to display the time afterwards, format your DateTime variable accordingly:
String format(DateTime value) {
return "${value.hour}:${value.minute}:${value.second}.${value.millisecond}";
}
I've mainly had to parse the String for calculations (difference) with other time values.
My domain class is
class RoomWantedAd{
Set<MateAgeRange> mateAgeRanges
static hasMany=[mateAgeRanges :MateAgeRange]
}
Her MateAgeRange is :
enum MateAgeRange {
TWENTIES('18-29')
,THIRTIES('30-39')
,FOURTIES("40-49")
,FIFTIES("50-59")
,SIXTIES("60+")
final String value
private MateAgeRange(String value) {
this.value = value
}
String toString() { value }
String getKey() { name() }
static belongsTo=[roomWanted:RoomWanted]
}
My problem is searching. In the search page, a person can select 0 or more values in [18-29, 30-39, 40-49, 50-59, 60+]. In the db, 0 or more values among [18-29, 30-39, 40-49, 50-59, 60+] are stored in field 'mateAgeRanges'.
Let db contains [30-39, 50-59] in 'mateAgeRange' field. Let in the search page, the user selects [18-29, 50-59, 60+]. Then the Ad corresponding to the above list must be returned. This is because at least one value in user's selection is present in the db list. How is it possible. Is it possible using an SQL query or grails GORM query.
you have to use exactly the same <g:select/> tag as you are using for create/update. Thus, you will see human readable values like THIRTIES in browser, but in the background the '30-39' values will be used.
I have XML data I am retrieving via a REST API that I am unmarshal-ing into a GO struct. One of the fields is a date field, however the date format returned by the API does not match the default time.Time parse format and thus the unmarshal fails.
Is there any way to specify to the unmarshal function which date format to use in the time.Time parsing? I'd like to use properly defined types and using a string to hold a datetime field feels wrong.
Sample struct:
type Transaction struct {
Id int64 `xml:"sequencenumber"`
ReferenceNumber string `xml:"ourref"`
Description string `xml:"description"`
Type string `xml:"type"`
CustomerID string `xml:"namecode"`
DateEntered time.Time `xml:"enterdate"` //this is the field in question
Gross float64 `xml:"gross"`
Container TransactionDetailContainer `xml:"subfile"`
}
The date format returned is "yyyymmdd".
I had the same problem.
time.Time doesn't satisfy the xml.Unmarshaler interface. And you can not specify a date fomat.
If you don't want to handle the parsing afterward and you prefer to let the xml.encoding do it, one solution is to create a struct with an anonymous time.Time field and implement your own UnmarshalXML with your custom date format.
type Transaction struct {
//...
DateEntered customTime `xml:"enterdate"` // use your own type that satisfies UnmarshalXML
//...
}
type customTime struct {
time.Time
}
func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
const shortForm = "20060102" // yyyymmdd date format
var v string
d.DecodeElement(&v, &start)
parse, err := time.Parse(shortForm, v)
if err != nil {
return err
}
*c = customTime{parse}
return nil
}
If your XML element uses an attribut as a date, you have to implement UnmarshalXMLAttr the same way.
See http://play.golang.org/p/EFXZNsjE4a
From what I have read the encoding/xml has some known issues that have been put off until a later date...
To get around this issue, instead of using the type time.Time use string and handle the parsing afterwards.
I had quite a bit of trouble getting time.Parse to work with dates in the following format: "Fri, 09 Aug 2013 19:39:39 GMT"
Oddly enough I found that "net/http" has a ParseTime function that takes a string that worked perfectly...
http://golang.org/pkg/net/http/#ParseTime
I've implemented a xml dateTime format conforming a spec, you can find it on GitHub: https://github.com/datainq/xml-date-time
You can find XML dateTime in W3C spec
A niche technique to override the JSON marshaling/unmarshaling of select keys in a struct is also applicable to XML marshaling/unmarshaling, with minimal modifications. The idea remains the same: Alias the original struct to hide the Unmarshal method, and embed the alias in another struct where individual fields may be overridden to allow the default unmarshaling method to apply.
In your example, following the idea above, I'd do it like this:
type TransactionA Transaction
type TransactionS struct {
*TransactionA
DateEntered string `xml:"enterdate"`
}
func (t *Transaction) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
const shortForm = "20060102" // yyyymmdd date format
var s = &TransactionS{TransactionA: (*TransactionA)(t)}
d.DecodeElement(s, &start)
t.DateEntered, _ = time.Parse(shortForm, s.DateEntered)
return nil
}
The smartest point of this method is, by sending TransactionS into DecodeElement, all fields of t gets populated through the embedded alias type *TransactionA, except for those overridden in the S-type. You can then process overridden struct members as you wish.
This approach scales very well if you have multiple fields of different types that you want to handle in a custom way, plus the benefit that you don't introduce an otherwise useless customType that you have to convert over and over again.
const shortForm = "20060102" // yyyymmdd date format
It is unreadable. But it is right in Go. You can read the source in http://golang.org/src/time/format.go