Skip to content
Stephan Bösebeck edited this page Nov 7, 2013 · 2 revisions

Index management in morphium

Morphium is capable of managing all indices, you might need for your database. In Mongo, indices are very, very important and the lack of which might increase the execution time of simple queries a log (like times 100). You can specify your indexes at class and field level. But you always must mark your entity with Indexes. Indexes will be created by morphium if you write your first data to a non existent collection. This is done to prevent morphium from creating new indexes on huge collections. You can enforce indexing for a given type by calling ensureIndexesFor

morphium.ensureIndexesFor(MyEntity.class);

Indexes can be specified on class level, and for a property - see those examples:

@Entity
@Index //just a marker
public class MyEntity {
   @Id String myId;
   @Index
   String name;
   
   @Index(options={"unique:true"})
   String uid;
}

In this example, there are three Indices defined, one on the ID, one on name and one on uid. All of them are defined in natural order. If you want to define an index, which consists of several fields, you need to do that at class level:

@Entity
@Index({"-name,uid","ts"}) //defining indices
public class MyEntity {
   @Id String myId;
   String name;
   long ts;
   
   @Index(options={"unique:true"})
   String uid;
}

In this case, one unique index for uid is defined, one compound index for name and uid (where name is sorted in reverse order), one single index for the field ts and one index for the ID of this entity. As you see, it's possible to define most of the indices in one @Index-Annotation at class level. Its also possible to add additional options, like 2d-Indexes or text indexes:

 @Index("position:2d")  //defining a gespacial index