【问题标题】:Indexing a MongoDB on Heroku, with Rails and Mongoid在 Heroku 上使用 Rails 和 Mongoid 索引 MongoDB
【发布时间】:2012-07-03 16:51:59
【问题描述】:

我有一个在 Heroku 上运行 Mongoid 的 Rails 应用程序,我需要设置一些索引以使数据库更快。我已经尝试在几个地方阅读它,并且我知道 Mongoid 有一些用于索引的内置函数,但我不确定应用它们的内容以及索引的频率。

我想索引的主要是我的设计模型:

scope :full_member_and_show, where(full_member: true).and(show: true).desc(:created_at)
scope :not_full_member_and_show, where(full_member: false).and(show: true).desc(:created_at)

embeds_many :comments
belongs_to :designer

search_in :tags_array

attr_accessible :image,  :tags, :description, :title, :featured, :project_number, :show



field :width
field :height
field :description
field :title
field :tags, type: Array
field :featured, :type => Boolean, :default => false
field :project_number, :type => Integer, :default => 0
field :show, :type => Boolean, :default => true
field :full_member, :type => Boolean, :default => false
field :first_design, :type => Boolean, :default => false

我需要索引什么,我该如何使用 Mongoid 进行索引以及应该多久进行一次索引?

错误更新

如果尝试索引以下内容:

index({ full_member: 1, show: 1 }, { unique: true })

它抛出了这个错误:

Invalid index specification {:full_member=>1, :show=>1}; should be either a string, symbol, or an array of arrays.

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb indexing mongoid


    【解决方案1】:

    您不需要定期建立索引:添加索引后,mongo 会随着集合的变化使该索引保持最新。这与 MySQL 或 Postgres 中的索引相同(您可能一直在考虑类似 solr)

    索引的内容取决于您将对数据集进行的查询。更新时索引确实会带来一些开销并消耗磁盘空间,因此您不想在不需要它们时添加它们。

    你通过索引告诉mongoid你想要什么索引,例如

    class Person
      include Mongoid::Document
      index :city
    end
    

    mongoid 文档中有大量关于 mongo 支持的各种索引的示例。

    然后你运行

    rake db:mongoid:create_indexes
    

    这确定了您想要的索引(基于对模型中index 的调用),然后确保它们存在于数据库中,并在必要时创建它们。在开发中,您将在向模型添加索引后运行它。在生产环境中,将其作为部署的一部分运行是有意义的(仅当您自上次部署以来添加了索引时才需要这样做,但系统地执行此操作会更容易)

    documentation 中有很多关于 mongo 如何使用索引的信息

    【讨论】:

    • 这么好的答案。正是我想要的。谢谢!我这样做是为了让我的数据库更快,所以我应该从我查询的每个字段中创建一个索引吗?这会是最好的做法吗?
    • Mongo 只使用单个索引来执行单个查询,因此如果您有一个引用 3 个字段的查询,它将不会使用 3 个单独的索引。但是,它可能能够使用复合索引。还有某些类型的查询(例如正则表达式查询)不能使用索引。 mongo 文档有大量关于 mongo 如何使用索引的信息
    • 好的。最好索引我们查询的第一件事吗?在这种情况下 - where(full_member: true)?
    • 在这种情况下,您最好在 [:full_member,:show,:created_at] 上使用复合索引,因为您的范围使用这三个。
    • 非常酷。我现在会接受你的回答。在哪里可以阅读更多关于 mongoid 中的复合索引的信息?
    猜你喜欢
    • 2012-08-09
    • 2011-12-03
    • 2023-03-26
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2013-04-10
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多