在 MongoDB 上实现自动完成 [英] Implement autocomplete on MongoDB

查看:21
本文介绍了在 MongoDB 上实现自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组用户,并希望对这些用户的用户名实现自动完成.我查看了 mongodb 文档,$regex 似乎是一种方法.有没有更好的办法?我所说的更好是指更高的性能/更好的实践.

Say I have a collection of users and want to implement autocomplete on the usernames of those users. I looked at the mongodb docs and $regex seems to be one way to do this. Is there a better way? By better I mean more performant/better practice.

推荐答案

根据@Thilo 的建议,您可以使用多种想法,包括前缀.

As suggested by @Thilo, you can use several ideas including prefixing.

最重要的是有非常快速的请求(因为您希望自动完成感觉即时).所以你必须使用查询来正确使用索引.

The most important thing is to have very quick request (because you want autocomplete to feel instaneous). So you have to use query which will use properly indexes.

使用正则表达式:使用 /^prefix/ (重要的是 ^ 指定行的开头,这是使查询使用索引所必需的).

With regexp : use /^prefix/ (the important thing is the ^ to specify the beginning of line which is mandatory to make the query use index).

范围查询也很好:{ $gt : 'jhc', $lt: 'jhd' } }

更复杂但更快:您可以在 mongo(又名尝试)中使用以下条目存储前缀树:

More complicated but faster : you can store prefix-trees in mongo (aka tries) with entries like :

 {usrPrefix : "anna", compl : ["annaconda", "annabelle", "annather"]}
 {usrPrefix : "ann", compl : ["anne", "annaconda", "annabelle", "annather"]}

最后一个解决方案非常快(当然如果在 compl 上有索引)但根本不节省空间.你知道你也选择权衡.

This last solution is very fast (if indexes on compl of course) but not space efficient at all. You know the trade-off you have too choose.

这篇关于在 MongoDB 上实现自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆