Paulo Silva
Paulo Silva

Reputation: 71

Search group of words in text field in CoreData

I am implementing an iOS app which contains a CoreData DB with one of the columns containing a text field, on which the user is supposed to perform several types of search (semantic, exact matches, among other options). Right now, I am stuck at trying to implement the following MySQL query (Python implementation):

'''select * from quotes where match section against ('\\"%s\\"' in boolean mode) ''' % (query)

The above query returns all the text rows containing all the words of string "query" without any particular order, as long as the text field contains all of the words. As an example, a query such as "tomorrow is Saturday" should find a match in a field containing the sentence "Saturday we are going somewhere. Tomorrow is Friday."

I have tried a few approaches, such as NSPredicate, and regex. I couldn't find a direct match in CoreData to the MySQL boolean mode, but the best I have been able to achieve so far was using regex with NSPredicate such as:

let queryArray = query.components(separatedBy: " ")
let regex = ".*\\b(" + queryArray.map {
    NSRegularExpression.escapedPattern(for: $0)
}.joined(separator: "|") + ")\\b.*"
let predicate = NSPredicate(format: "textField MATCHES %@", regex)

However, this query is returning any textField row that contains one or more of the words in the initial query, which is not the desired result in my case.

How can I achieve the desired result in CoreData?

Upvotes: 1

Views: 146

Answers (1)

Paulo Silva
Paulo Silva

Reputation: 71

For those that may get stuck, NSCompoundPredicate did the trick for me, just create an array of predicates, where which NSPredicate instance is looking for one of the words in the string, ignoring case and apply the NSCompoundPredicate to the NSFetchRequest.

Upvotes: 1

Related Questions