create indexes for search using MongoTemplate?

user5268786 picture user5268786 · Oct 14, 2015 · Viewed 9.1k times · Source

how we can create Indexes for the following query using MongoTemplate? I am referring to site http://docs.mongodb.org/v2.4/tutorial/search-for-text/ they've not given any details about how we can create Indexes using MongoTemplate?

db.getCollection('user').ensureIndex({ firstName: "text", middleName : 
"text", lastName : "text",emailId:"text" });

Answer

chridam picture chridam · Oct 14, 2015

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;
}