Skip to content

Indices in Morphium

Stephan Bösebeck edited this page Aug 23, 2013 · 4 revisions

Ensure Index in Morphium

The easiest way to make sure that indices are in place is by calling the method morphium.ensureIndex(). This one creates one index on the given Collection (or Entity respectively). Usage is as follows:

   morphium.ensureIndex(UncachedObject.class,"-timestamp","name"); //will create on combined index
   morphium.ensureIndex(CachedObject.class,CachedObject.Fields.counter); //will create on +1 index on this type
   Map<String, Integer> complexIndex=new HashMap<String,Integer>(); //Make it a sorted map, if necessary!

Be careful: Index creation might cause your Mongo to freeze for a while depending on the size of your collections.

Automatic Index creation

Morphium supports automatic index creation. But those indexes are only created, when the collection is about to be newly created (usually, this is what you want, especially in conjunction with the new NameProvider support). Just add the annotations to your type or field to have it indexed:

  public class MyLog  {
     private long timestamp;
     private String hostName;
     private String level;
     public List<Double> position;
     private String id;
     private String uniqueField;
     //additional fields and methods

This will create several indexes, if the collection is about to be created (and only then):

  • timestamp
  • timestamp and level
  • host_name and timestamp
  • hostname, level and timestamp (-1)
  • host_name
  • a 2D-Index for geospacial search on the field position
  • and a unique index for the unique_field

When you have added the Index-Annotation to your entities, you can also use the Method morphium.ensureIndex(MyEntity.class) to honor those calls. This will ensure indices now, no matter whether the collection exists or not (use with care!)

You can’t perform that action at this time.