Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data - MongoDB indexing DBRef

I'm using spring-data-mongodb-1.2.0.RELEASE. I have two classes A and B where B has a reference to A and it is annotated with @DBRef.

Class A:

@Document(collection = "a")
public class A {
@Id
public String id;

/** The TicketGrantingTicket this is associated with. */
@Field
public String name;

public A(String id, String name) {
    this.id = id;
    this.name = name;
}
}

Class B:

@Document(collection = "b")
public class B {

@Id
public String id;

@Field
public String name;

@DBRef
@Indexed
public A a;

public B(String id, String name, A a) {
    super();
    this.id = id;
    this.name = name;
    this.a = a;
}
}

Since I'm quering for all instances of B that are refering to a certain A:

B fromDB = mongoOperations.findOne(Query.query(Criteria.where("a.$id").is(a1.id)), B.class);

I need it to be indexed.

After the first insertion of a B instance into MongoDB an index should be created. As can be seen below it doesn't:

Does anyone know how can I create such an index ?

In addition it looks like the DBRef filed (as can be seen by the mongo shell) does not match to the format as it is defined at MongoDB documentation.

Am I missing something here?

like image 786
Modi Avatar asked Apr 04 '13 18:04

Modi


2 Answers

DBObject indexOptions = new BasicDBObject();
indexOptions.put("a", 1);
indexOptions.put("b", 1);
indexOptions.put("c.d", 1);
indexOptions.put("e.f", 1);
CompoundIndexDefinition indexDefinition =
            new CompoundIndexDefinition(indexOptions);
mongoTemplate.indexOps(.class).ensureIndex(indexDefinition);

for unique index you can add mongoTemplate.indexOps(.class).ensureIndex(indexDefinition).unique();
like image 151
saurabh Avatar answered Sep 23 '22 06:09

saurabh


You can create the index with the mongo shell, but if you want to do it through code and since you are using spring-data-mongodb, use this:

mongoTemplate.indexOps(B.class).ensureIndex(new Index().on("a", Order.ASCENDING));

You can also specify the name of the collection if the name of your class doesn't match it:

mongoTemplate.indexOps("b").ensureIndex(new Index().on("a", Order.ASCENDING));
like image 45
AntonioOtero Avatar answered Sep 24 '22 06:09

AntonioOtero