ioscore-datanspredicatensfetchrequestnscompoundpredicate

Fetching entities whose many-to-many relationship contains all terms


I have a model with a Verse entity that has a many-to-many relationship to a Word entity.

I'd like to find verses that contain all words that a user is searching for.

I'm guessing that it could be done with a predicate like

    "ANY words.word == %@ AND ANY words.word == %@ AND ...", term1, term2, ...

Can this use some type of word->Verse index, to avoid having to compare every verse's words against term1?

If not, how should the (model or) predicate be changed to make this fetch more efficient?


Solution

  • First, you can just do a contains in one predicate:

    [NSPredicate predicateWithFormat:"ANY words.word CONTAINS %@", arrayOfWords];
    

    But, that will be slow. String compares are slow. Case and diacritic insensitive are almost the slowest. You are better off having another property on your Word entity that is for searching where you strip out the case and the diacritic and then search against that field. Your search performance will be much higher.