8

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" });
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259

3 Answers3

12

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;
}
chridam
  • 100,957
  • 23
  • 236
  • 235
8

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());

Community
  • 1
  • 1
saurabh
  • 2,463
  • 1
  • 18
  • 8
0

In spring mongodb 2.0.1

    TextIndexDefinition textIndex = new TextIndexDefinition.TextIndexDefinitionBuilder().onField(indexName).build();

    mongoTemplate.indexOps(DINMonitorLog.class).ensureIndex(textIndex);
jprism
  • 3,239
  • 3
  • 40
  • 56