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");
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; }
source share