indexOps 和 @Indexed 有什么区别
what is the difference between indexOps and @Indexed
我正在阅读 Spring Data MongoDB 的文档,我看到了两种不同的创建索引的方法:使用 indexOps
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
或通过注释@Indexed
和其他(@CompoundIndex
、@GeoSpatialIndexed
、@TextIndexed
)
我的问题是:这两种方法有什么区别,how/when 我应该使用一种还是另一种
这两种方法(@Indexed
和 ().ensureIndex(...)
)实现了相同的目标,唯一的区别是一种是声明式的,另一种是命令式的。来自 documentation:
the @Indexed
annotation tells the mapping framework to call
createIndex(…) on that property of your document, making searches
faster.
并且来自MongoTemplate
的代码(特别是DefaultIndexOperations#ensureIndex
):
collection.createIndex(indexDefinition.getIndexKeys())
一般来说,如果可能的话,我更喜欢注释方法,因为它在实体级别上更可见,也更易读。另一方面,编程方法可用于不在实体中的字段。例如,在一个项目中,我们有这样的隐藏字段用于搜索(即小写和连接)需要一个索引,我们使用 java 代码创建它们。
我正在阅读 Spring Data MongoDB 的文档,我看到了两种不同的创建索引的方法:使用 indexOps
mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));
或通过注释@Indexed
和其他(@CompoundIndex
、@GeoSpatialIndexed
、@TextIndexed
)
我的问题是:这两种方法有什么区别,how/when 我应该使用一种还是另一种
这两种方法(@Indexed
和 ().ensureIndex(...)
)实现了相同的目标,唯一的区别是一种是声明式的,另一种是命令式的。来自 documentation:
the
@Indexed
annotation tells the mapping framework to call createIndex(…) on that property of your document, making searches faster.
并且来自MongoTemplate
的代码(特别是DefaultIndexOperations#ensureIndex
):
collection.createIndex(indexDefinition.getIndexKeys())
一般来说,如果可能的话,我更喜欢注释方法,因为它在实体级别上更可见,也更易读。另一方面,编程方法可用于不在实体中的字段。例如,在一个项目中,我们有这样的隐藏字段用于搜索(即小写和连接)需要一个索引,我们使用 java 代码创建它们。