Spring 数据 Mongo - 执行常规搜索?

Spring Data Mongo - Perform Regular Search?

我浏览了很多这样的链接:How to create full text search query in mongodb with spring-data?,但没有得到正确的方法。

我有一个包含 1000 个文档的 Employee 集合。我想提供执行搜索 ignorecase 的功能,当我搜索 ra 时,我应该得到 Ravi、Ram、rasika 等名称。

我使用了下面的逻辑,效果很好,但我想从性能的角度来理解。还有比这更好的解决方案吗?

Query query = new Query(Criteria.where("employeeName").regex("^"+employeeName, "i")); 

您可以使用正则表达式在应用查询过滤器的字段上创建索引。例如,考虑 person 集合中的文档:

{ "name" : "ravi" }
{ "name" : "ram" }
{ "name" : "John" }
{ "name" : "renu" }
{ "name" : "Raj" }
{ "name" : "peter" }

以下查询(运行 来自 Mongo Shell)查找并获取名称以字母 "r" 或 "R" 开头的四个文档:

db.person.find( { name: { $regex: "^r", $options: "i" } } )

但是,查询执行集合扫描,name 字段上没有索引。因此,在该字段上创建一个索引。

db.person.createIndex( { name: 1 } )

现在,运行查询并为同一个查询生成查询计划(使用explain())。查询计划显示它是 IXSCAN(索引扫描)。而且,这将是一个高效执行的查询。

请注意,在索引字段上进行前缀搜索(如上述使用 ^ 的查询)会加快查询速度。

来自documentation

For case sensitive regular expression queries, if an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

尽管文档说明如下(见下段),但我 运行 的查询确实使用了索引,并且使用 explain() 生成的查询计划显示了索引扫描。

Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes.