【问题标题】:How to read multikey index values in MongoDB?如何在 MongoDB 中读取多键索引值?
【发布时间】:2013-06-17 22:55:40
【问题描述】:

我想要 自动完成 功能,从数据库中建议 关键字。如果我使用 MongoDB 和 multikey index,我的数据库中已经有这些关键字,但我可以以某种方式访问​​它们吗?

如果我在集合中有以下对象:

{
    "title": "Some awesome title",
    "keywords": [
        "some",
        "awesome",
        "title"
    ]
}

我有多键索引:

db.somecollection.ensureIndex({ "keywords" : 1 }) 

所以索引将包含以下值:

"some"
"awesome"
"title"

如果用户在自动完成控件中输入“s”字母,应用程序应该建议“some”关键字。我可以从索引中搜索关键字吗?或者我应该怎么做?

【问题讨论】:

  • 我建议使用 ElasticSearch 或 Solr,因为这不是 MongoDB 目前非常擅长的。

标签: mongodb indexing multikey


【解决方案1】:

您可以选择使用聚合框架:

DEV:history:PRI > db.test.find()
{ "_id" : ObjectId("51c37c0c20d107378f9af3cc"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "title" ] }
{ "_id" : ObjectId("51c37de420d107378f9af3ce"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "something" ] }
{ "_id" : ObjectId("51c37f1920d107378f9af3cf"), "title" : "Some awesome title", "keywords" : [ "something", "awesome", "someone" ] }
DEV:history:PRI > db.test.aggregate({$match : {keywords : /^som/}}, {$project:{keywords:1, _id : 0}}, {$unwind : "$keywords"}, {$match : {keywords : /^som/}}, {$group: {_id : '$keywords', count : {$sum : 1}}})
{
    "result" : [
        {
            "_id" : "someone",
            "count" : 1
        },
        {
            "_id" : "something",
            "count" : 2
        },
        {
            "_id" : "some",
            "count" : 2
        }
    ],
    "ok" : 1
}

注意:未涵盖多键索引,并且已经提交了一些 JIRA 问题。因此,尽管使用了索引,但不包括查询(对于多键索引)

我们可以选择使用“计数”参数来决定显示自动完成的顺序。如果不需要,请从查询中删除。

【讨论】:

  • 感谢您的回答。通过这种方式我可以真正读取值,所以我认为这是正确的答案。虽然对于更大的集合来说这可能会很慢,所以我尝试使用 Redis(除了 MongoDB)来解决这个问题。
猜你喜欢
  • 2011-11-15
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 2014-02-18
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
相关资源
最近更新 更多