create indexes for search using MongoTemplate?
Suppose your entity User
is modelled as
@Document
class User {
String firstName;
String middleName;
String lastName;
String emailId;
}
and want to have a text index based on its firstName, middleName, lastName and emailId fields, the raw MongoDB index definition would look something like this:
{
firstName: "text",
middleName: "text",
lastName: "text",
emailId: "text"
}
To create a text index on the fields above you want to have full text search enabled on, do the following
TextIndexDefinition textIndex = new TextIndexDefinitionBuilder()
.onField("firstName")
.onField("middleName")
.onField("lastName")
.onField("emailId")
.build();
MongoTemplate mongoTemplate = new MongoTemplate(new Mongo(), "database"); // obtain MongoTemplate
mongoTemplate.indexOps(User.class).ensureIndex(textIndex);
Or you can create the index automatically through mapping annotations:
@Document
class User {
@TextIndexed String firstName;
@TextIndexed String middleName;
@TextIndexed String lastName;
@TextIndexed String emailId;
}
Easiest way to create indexes in mongo using spring Java will be:
// Define ur mongo template defination
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(<Classname>.class).ensureIndex(indexDefinition);
A unique index can be configured on the index definition:
mongoTemplate.indexOps(<Classname>.class).ensureIndex(indexDefinition.unique());