create indexes for search using MongoTemplate? create indexes for search using MongoTemplate? mongodb mongodb

create indexes for search using MongoTemplate?


Suppose your entity User is modelled as

@Documentclass 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 MongoTemplatemongoTemplate.indexOps(User.class).ensureIndex(textIndex);

Or you can create the index automatically through mapping annotations:

@Documentclass 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 definationDBObject 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());


In spring mongodb 2.0.1

    TextIndexDefinition textIndex = new TextIndexDefinition.TextIndexDefinitionBuilder().onField(indexName).build();    mongoTemplate.indexOps(DINMonitorLog.class).ensureIndex(textIndex);