Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Indexed annotation ignored when using named collections

I have a pojo annotated like this:

@Document
class Car {

  @Id
  String id ;

  @Indexed
  String manufacturer ;

}

And I am using MongoTemplate to insert into mongo. If I insert without specifying a collection name, everything works fine. However, if I specify a collection name, none of the indexes are created except for the _id one.

I really need to be able to specify the collection name manually because:

  • I need to ensure different subclasses of Car end up in the same collection
  • I would like to store each year's worth of Cars in a separate collection

Do I have to call ensureIndex() myself manually? If so, is there a way to do it that uses my @Indexed annotations? The actual objects I am trying to save are a lot more complex than 'Car'

like image 434
Dave Avatar asked Jul 29 '13 01:07

Dave


2 Answers

Unfortunately MongoTemplate function

public void insert(Object objectToSave, String collectionName)

using collectionName only for saving object and not for creating any annotated indexes. If object passed to save operation then application event listener MongoPersistentEntityIndexCreator scan saved entity class for @Indexed annotations and create indexes. But it detect collection name based on next formula (from sources):

String collection = StringUtils.hasText(index.collection()) ? index.collection() : entity.getCollection();

where index.collection() is collection from @Indexed annotation and entity.getCollection() from @Document annotation.

So, you need to call ensureIndex() manually. It's strange behaviour. I think you can open bug here: DATAMONGO

EDIT: I think you can create function that return all classes annotated with @Document and also get all collections from mongodb started from cars.<year>. Then you can analyse all fields annotated with @Indexed and, as result, call ensureIndex for this fields using collections list.

like image 175
seralex.vi Avatar answered Nov 05 '22 09:11

seralex.vi


I really need to be able to specify the collection name manually because:

I need to ensure different subclasses of Car end up in the same collection
I would like to store each year's worth of Cars in a separate collection

As for your first statement, you can enforce a single collection using @Document metadata annotation:

@Document(collection="cars")
class Car {

    @Id
    String id ;

    @Indexed
    String manufacturer ;

}

@Document(collection="cars")
class Honda extends Car {

}

@Document(collection="cars")
class Volvo extends Car {

}

The collection field of @Document will take care that every subclass of car gets into the cars collection, plus the index is automatically created with the help of the @Indexed annotation.

like image 43
Ori Dar Avatar answered Nov 05 '22 09:11

Ori Dar