title: CoreData performance: predicate on more to-many relationships
body: <p>Using SQL data store, I have a model like this:</p>
  
  <p>Category &lt;-->> Item</p>
  
  <p>Collection &lt;-->> Item</p>
  
  <p>Brand &lt;-->> Item</p>
  
  <p>Every left-side entity has a to-many relationship named <strong>items</strong> to the Item entity. Each one is the inverse of to-one Item relationships <strong>category</strong>, <strong>collection</strong> and <strong>brand</strong> respectively.</p>
  
  <p>I want to fetch all Brand objects with at least one Item in relation with a particular Collection AND a Category. In natural language, I want all the brands of items with  particular category and a particular collection.</p>
  
  <p>Given the objects <em>Category</em> *<em>myCategory</em> and <em>Collection</em> *<em>myCollection</em>, I use to build a predicate on the Brand entity in this way:</p>
  
  <pre><code>NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"(ANY items.category == %@) AND (ANY items.collection == %@)",myCategory,myCollection]; 
  </code></pre>
  
  <p>And I get the correct results. The problem is performance. Too slow! And I simplified the question for three levels! Let's consider four levels in a iOS multilevel catalog: the app shows categories available, user select a category, the app shows collections in that category, user select a collection, the app shows brands in that collection (and the category already selected), user select a brand, the app shows for example materials in that brand,collection and category... </p>
  
  <p>To be honest, i use NSCompoundPredicate to put in AND subpredicates at every user selection, building dynamically the final predicate. But this doesn't matter for the purpose of the question.</p>
  
  <p>There are more than 30,000 (30k) objects of <strong>Item</strong> entity in the sql data store, and using AND between <strong>items</strong> relationship is very slow (I noticed 7-10 seconds of lag to show brands in the example above).</p>
  
  <p>I would try to:</p>
  
  <p>-remove <strong>items</strong> relationships from Category, Collection and Brand entites</p>
  
  <p>-on the Item entity, replace <strong>category</strong>, <strong>collection</strong> and <strong>brand</strong> relationships with fetched properties on attributes like "category_id", "collection_id" and "brand_id".</p>
  
  <p>-use keypath or predicates to fetch the brands without using to-many relationships.</p>
  
  <p>Before I start to destroy and remake the whole work of the last 6 months, do you have any suggestion? :)</p>
  
  <p>Thank you!</p>