I want to perform partial match like the clause LIKE do in SQL.
In Magical Record, to look for values for a specified field, we use findByAttribute:
NSArray *productsFoundByTitle = [Product MR_findByAttribute:#"product_title" withValue:#"bags"];
The problem is that this will return only exact matches of bags in product_title. I want to return also partial matches so a value like : mail bags would also be returned.
How can I do that in MagicalRecord?
Best solution I came with so far is the following: Grap all data, and find all Partial matches with rangeOfString function:
NSArray *allResults = [Product MR_findAll];
for (id element in allResults) {
if ([[element valueForKey:#"product_title"] rangeOfString:#"bags" options:NSCaseInsensitiveSearch].location != NSNotFound) {
//I got a partial match, save this instance for later use
}
}
I suggest you read up about predicates. There are key words you're looking for such as startswith, endswith, and like. Check out the predicate programming guide
Related
Give a table User_DNA and column a sequence,
I want to write a query such that if data in the sequence column matches or is prefix of the search query term, it should return an item found or true.
e.g,
sequence
dog
hor
cat
tig
cat
if my search query is doga (has dog as prefix in db), horrible(has hor as prefix in db),tiger(has tig as prefix in db), caterpillar(has cat as prefix in db), the query should return true as all these search queries have prefixes in the database.
What should my sql search query?
Thanks
If you use Room, you can try this (using Kotlin):
#Query("select * from User_DNA WHERE sequence LIKE :search")
fun getItem(search: String): UserDNA?
Setting your search parameter to this method you should put the search pattern as "[your search string]%", for example: "dog%"
if my search query is dog, the query should return true or one of the
items (dogsequence/doggysequence) what ever is efficient
You can check result of the query - if it's null, then there are no matching values in your column.
UPDATED
If you want to find "hor" with "horrible" I can propose next way (maybe it's a task for RegExp but honestly I haven't used it in ROOM):
You can put two methods in your DAO. One method is auxiliary, its task - is ti fill a list with words, that we want to find. For example, for pattern "horrible" that method should prepare list with {"horrible", "horribl", "horrib", "horri", "horr", "hor"}.
Second method should fetch a result from SQLite where your fields holds value from the list prepared on step1. This method should be annotated with Room annotation.
So first method prepares list, invokes query for searching word in SQLite and returns it to ViewModel (or Repository).
Something like this:
#Query("select * from User_DNA WHERE sequence IN (:search) ORDER BY sequence")
fun getItem(search: List<String>): User_DNA?
fun findItem(search: String): User_DNA? {
val searchList = mutableListOf<String>()
val minimalStringLength = 2 // it's up to you, maybe 1?
while (search.length > minimalStringLength) {
searchList.add(search)
search = search.dropLast(1)
}
return getItem(searchList.toList())
}
With JSONPath, how can you extract a single value from a list of known keys?
For example, I want to write one JSON path expression that can extract Sean from all three of these JSON documents:
{ "firstName": "Sean" }
{ "first_name": "Sean" }
{ "first_name": "Sean", "firstName": "Sean" }
This example is a little contrived, but I have an actual use case that requires this behavior.
The best I can come up with is the expression $.firstName,first_name which will work for #1 and #2 but returns an array for #3 — and I just want the first value that matches.
Basically, I’m looking for a JSONPath extract expression that simulates this JavaScript code:
json.firstName || json.first_name
I believe you want something like below :)
You can get json path using the index .Whn I'm using rest-assured I always use something similar to below code to extract values from my json response .
Response response=given().contentType(ContentType.JSON).get("http://localhost:3000/posts");
JsonPath jsonPathEvaluator = response.jsonPath();
String fn1 = jsonPathEvaluator.get("firstName[0]");
String fn_1=jsonPathEvaluator.get("first_name[0]");
String fn2=jsonPathEvaluator.get("firstName[1]");
You can pass all pair to dict and then extract your values or if you need only values you can use set structure to store keys and separate list to values.
I'm trying to use the update_item functionality for DynamoDB in boto3.
I'm struggling right now to update lists for items. I would like to create a new list if the list does not exist yet and otherwise append to the existing list.
Using an UpdateExpression of the form SET my_list = list_append(my_list, :my_value) returns an error "The provided expression refers to an attribute that does not exist in the item" if the list does not exist yet.
Any idea how I would have to modify my UpdateExpression?
You can use list_append(if_not_exists()) construction.
UpdateExpression:
'SET my_list2 = list_append(if_not_exists(my_list2, :empty_list), :my_value)'
ExpressionAttributeValues:
{ ":my_value":{"L": [{"S":"test"}]}, ":empty_list":{"L":[]} }
Update: as mentioned in the comments, boto3 now raises an error for the expression above and a version without explicit types works: { ":my_value": ["test"], ":empty_list":[] }.
An alternative to Boris solution could be to use set instead of list datatype and use the ADD keyword, it does exactly what you want.
With Add, the update expression becomes: ADD setName :s
And the expression attribute values can be like: {":s": {"SS":["First", "Second"]}}
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.ADD
I need to serialize arbitrary records into maps/dictionary.
I imagine my end type look like this:
type TabularData= array<Map<string, obj>>
But I have problems in build a generic function that accept any record and turn them into Map.
In practice, the best advice is probably to use some existing serialization library like FsPickler. However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go.
The following takes a record and creates a map from string field names to obj values of the fields. Note that it does not handle nested records and it is not particularly fast:
open Microsoft.FSharp.Reflection
let asMap (recd:'T) =
[ for p in FSharpType.GetRecordFields(typeof<'T>) ->
p.Name, p.GetValue(recd) ]
|> Map.ofSeq
Here is a little example that calls this with a simple record:
type Person =
{ Name : string
Age : int }
asMap { Name = "Tomas"; Age = -1 }
Using the same idea mentioned by Tomas, you can create a IDictionary<K,V> from a record like this:
let asDictionary (entity: 'T) =
seq {
for prop in FSharpType.GetRecordFields(typeof<'T>) ->
prop.Name, prop.GetValue(entity)
} |> dict
I have an Enumeration class, and have extracted "id" values from some of the members and stored them in Int variables. Whether that was a good idea/not is not the question.
What the question is, is why I cant seem to do the following:
Let's say I have s : Int which holds one of these id values ... and I would like to do matching against the actual enumeration values. Something like the following:
s match {
QID.MEM_RD.id => // something
QID.MEM_WRT.id => // something else
}
This seems to give me a failure that "stable identifier is required". So I end up writing code like
if (s == QID.MEM_RD.id)
// something
else if (s == QID.MEM_WRT.ID)
// something else
So .. it's just kind of odd to me that Scala has this nice feature, but appears to force me to go back to an uglier style of coding --- when I would much rather use their match feature.
Any ideas? I guess I can restructure to stop extracting ids ... but it's just the idea that match doesn't allow this that irks me a bit.
(Note: I don't try to store the id values anywhere persistently ... just use them for the duration of program execution.)
-Jay
I think you can use if guards in that case.
s match {
case a if (s == QID.MEM_RD.id) => println("you read!")
case b if (s == QID.MEM_WRT.id) => println("you wrote!")
}
http://programming-scala.labs.oreilly.com/ch03.html#PatternMatching