Compound Indexes with Entity Inheritance

Our data model uses entity inheritance where the top-level entity is abstract and includes the attributes common to all the other (sub)entities. We've trying to improve fetch performance on sub-entities by adding compound indexes but are not getting satisfaction.


Examining the sqlite schema shows that there is a single table that includes all attributes from the super-entity plus all attributes form the sub-entities. A sqlite column named "z_ent" is added by core data and used to identify the applicable sub-entity for a sqlite record.

Using sqlite "explain query plan" on select statements, we've discovered that compound indexes added to a sub-entity are not used, and the only index used is one for "z_ent". However we've also discovered that adding the text "self" to the compound indexes attribute list will create compound indexes in sqlite that include "z_ent" as well as the other specified attributes, which results in a useful index.

The problem is that the generated compound index only includes "z_ent" when the app is initially installed. If core data migrates the database and creates the new compound indexes, "z_pk" is used instead of "z_ent" and the query plan does not use the indexes.

Anyone have suggestions regarding adding compound indexes to core data when entity inheritance is used?

Answered by randy in 246401022

For them that care: using the keyword "entity" (rather than "self") as the first item in a compound index generates the proper index.

First things first.

File a bug report in the bug reporter concerning the defect you've found with the database migration code. Then post your bug report number. For good measure, please note which versions of iOS or OS X you're seeing the bug happen in.


Do you see the same loss of index on both automatic migrations and heavy weight migrations?

Bug reported as 31147976.

This occurs on both ios 9.3.5 (ipad mini) and 10.2.1 (iphone 5S)

Only a "lightweight" migration was tested as the only change to the data model was adding the compound indexes.

Same behaviour in iOS 10.3

Accepted Answer

For them that care: using the keyword "entity" (rather than "self") as the first item in a compound index generates the proper index.

Compound Indexes with Entity Inheritance
 
 
Q