实施MongoDB的自动完成 [英] Implement autocomplete on MongoDB

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

问题描述

说我有用户的集合,要实现这些用户的用户名自动完成。我看了看MongoDB的文档和$正则表达式似乎是做到这一点的方法之一。有没有更好的办法?通过更好地我的意思是更好的性能/更好的做法。

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建议,可以使用一些想法,包括prefixing。

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'}}

更复杂,但速度更快:你可以像条目存储在蒙戈preFIX树(又名尝试):

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"]}

这最后的解决方案是非常快的(如果在过程中的并发症指标),但是空间效率不高的。你知道权衡你有太多选择。

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天全站免登陆