Reputation: 438
I want to write a CoreData
Predicate to check how many records from a column matches with any of the keywords entered irrespective of order in which they appear.
Ex. Suppose I have a record with "This is my test string to compare", now if I search with "test my compare" it should return this record.
I have tried using separating the words and using CONTAINS
for each word and OR
ed , but it is taking forever for result to come as there are more than 15000 records in db.
Please help.
Upvotes: 1
Views: 412
Reputation: 119
// MARK: Step:1 this function will return predicate
func getPredicate(searchStr: String) -> NSPredicate {
var searchPredicate = NSPredicate()
var pridicateArray = [NSPredicate]()
if searchStr.contains(find: " ") {
for searchWord in searchStr.components(separatedBy: " ") {
let newPredicate = NSPredicate(format: "SELF.searchable contains[c] %@", searchWord)
pridicateArray.append(newPredicate)
}
searchPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: pridicateArray)
} else {
searchPredicate = NSPredicate(format: "SELF.searchable contains[c] %@", searchStr)
}
return searchPredicate
}
// MARK: Step:2 assign predicate to core data fetch request like below
fetchRequest.predicate = self.getPredicate(searchStr: "multi word string")
Upvotes: 0
Reputation: 2470
Create contains predicate
for each word in the string and Use NSCompoundPredicate
of AND type.
let string = "test my compare"
var pridicateArray : [NSPredicate]!
for word in string.components(separatedBy: " ") {
let newPredicate = NSPredicate(format: "YOUR_ENTITY contains[c] %@", word)
pridicateArray.append(newPredicate)
}
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: pridicateArray)
Upvotes: 1