create indexes for search using MongoTemplate?
Asked Answered
E

3

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" });
Encarnalize answered 14/10, 2015 at 14:22 Comment(0)
P
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;
}
Paraldehyde answered 14/10, 2015 at 14:41 Comment(0)
T
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());

Turnstile answered 2/6, 2016 at 9:19 Comment(0)
K
0

In spring mongodb 2.0.1

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

    mongoTemplate.indexOps(DINMonitorLog.class).ensureIndex(textIndex);
Kenspeckle answered 10/11, 2017 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.