user1904273
user1904273

Reputation: 4764

Core Data Find Single Match on Two Attributes

This use case should be reasonably common but I can't seem to figure it out or find any ways to solve it on the web. I would like to search an employee database using natural language, ie an unstructured word string.

Let's say you have a core data entity with three attributes as follows:

firstname string
lastname string
Employee_id string

And you have the following managed objects

Jane | Smith | 1
Jane | Smiley | 2
Jane | Doe | 3
John | Doe | 4
Richard | Doe | 5

How would you get the employee-id for the string 'Jane Doe' or 'Doe Jane' or 'Doe Jane accounting'?

If you knew for sure that there were just two words and the order was firstname, second name then you could do.

NSArray *words = [string componentsSeparatedByString:@" "];   
NSPredicate *pred = [NSPredicate predicateWithFormat:@"firstname beginswith[cd] %@ AND lastname beginswith[cd]", words[0],words[1]];

But in this case, I don't know the order or number of words.

Thanks in advance for any suggestions.

Upvotes: 0

Views: 45

Answers (1)

Dad
Dad

Reputation: 6478

You can use NSCompoundPredicate and put a bunch of NSPredicates with the various ordering possibilities like the one you made in your example, but that will obviously be limited to the number of words you want to write predicate combinations for.

(probably obviously, but you are creating a series of predicates like: ( (stringA and string B) or (stringB and stringA), or (stringA and stringC) or (stringC and stringA) or (stringB and stringC) or (stringC and stringB) ).

You can create these predicates relatively cleanly by writing a predicate with variables and then using predicateWithSubstitutionVariables: repeatedly with different dictionary of variable -> word mappings to get the various arrangements.

The trick is, at some point you are trying to do free form full text searching across structured data without a full text index. Here's a decent blog post (though old) on the challenges of doing that.

An alternative is to design your user interface to get the user to you the data in an easier form to deal with. For example, give the user a form for their query with the valid fields to fill in. Or at least direct them with prompt text for your open entry single text field with something like "Enter the person's first and last name" or whatever makes sense.

Upvotes: 1

Related Questions