Create indexes for searches using MongoTemplate?

how can we create Indexes for the next query using MongoTemplate ? I mean the site http://docs.mongodb.org/v2.4/tutorial/search-for-text/ , it did not give any details on how we can create indexes using MongoTemplate?

 db.getCollection('user').ensureIndex({ firstName: "text", middleName : "text", lastName : "text",emailId:"text" }); 
+5
source share
3 answers

Suppose your User entity is modeled as

 @Document class User { String firstName; String middleName; String lastName; String emailId; } 

and you want to have a text index based on its fields firstName, middleName, lastName and emailId, the raw MongoDB index definition will look something like this:

  { firstName: "text", middleName: "text", lastName: "text", emailId: "text" } 

To create a text index in the fields above where you want to enable full-text search, 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 automatically create an index through display annotations:

 @Document class User { @TextIndexed String firstName; @TextIndexed String middleName; @TextIndexed String lastName; @TextIndexed String emailId; } 
+6
source

The easiest way to create indexes in mongo using spring Java:

 // Define ur mongo template defination DBObject indexOptions = new BasicDBObject(); indexOptions.put("a", 1); indexOptions.put("b", 1); indexOptions.put("cd", 1); indexOptions.put("ef", 1); CompoundIndexDefinition indexDefinition = new CompoundIndexDefinition(indexOptions); mongoTemplate.indexOps(<Classname>.class).ensureIndex(indexDefinition); 

A unique index can be configured to define the index: mongoTemplate.indexOps(<Classname>.class).ensureIndex(indexDefinition.unique());

+4
source

In spring mongodb 2.0.1

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

Source: https://habr.com/ru/post/1233708/


All Articles