我们如何Indexes使用以下查询创建MongoTemplate?我指的是网站http://docs.mongodb.org/v2.4/tutorial/search-for-text/他们没有提供有关如何使用MongoTemplate创建索引的任何细节?
db.getCollection('user').ensureIndex({ firstName: "text", middleName :
"text", lastName : "text",emailId:"text" });
Run Code Online (Sandbox Code Playgroud)
假设您的实体User被建模为
@Document
class User {
String firstName;
String middleName;
String lastName;
String emailId;
}
Run Code Online (Sandbox Code Playgroud)
并希望有一个基于firstName,middleName,lastName和emailId字段的文本索引,原始的MongoDB索引定义如下所示:
{
firstName: "text",
middleName: "text",
lastName: "text",
emailId: "text"
}
Run Code Online (Sandbox Code Playgroud)
要在上面的字段中创建文本索引,您希望启用全文搜索,请执行以下操作
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);
Run Code Online (Sandbox Code Playgroud)
或者您可以通过映射注释自动创建索引:
@Document
class User {
@TextIndexed String firstName;
@TextIndexed String middleName;
@TextIndexed String lastName;
@TextIndexed String emailId;
}
Run Code Online (Sandbox Code Playgroud)
使用spring Java在mongo中创建索引的最简单方法是:
// 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);
Run Code Online (Sandbox Code Playgroud)
可以在索引定义上配置唯一索引:
mongoTemplate.indexOps(<Classname>.class).ensureIndex(indexDefinition.unique());
| 归档时间: |
|
| 查看次数: |
5668 次 |
| 最近记录: |