Ruby on Rails, ActiveRecord, Binary search

 ̄綄美尐妖づ 提交于 2019-12-13 04:17:12

问题


If I had the following table.

create_table :my_table, :id => false do |t|
   t.string :key_column
   t.string :value_column
end

How would I ensure that the rows are optimaly stored for binary search by the field of :key?

And how would I make sure binary search is used?


回答1:


For any interesting number of rows, the optimal way (for most definitions of "optimal") to access a single random record by key is to create an index.

CREATE INDEX my_index ON my_table ( key_column );

or in an ActiveRecord migration:

add_index(:my_table, :key_column)

Database indices typically use binary search, using B-trees or similar, which offers a good balance between storage costs and time for retrieval and update.

Ensuring the index is used should be relatively straightforward for single-table operations:

MyTable.find_by_key_column('ABC123')

for example, should generate something like this (check development.log):

SELECT * FROM my_table WHERE (key_column = 'ABC123')

which even MySQL's relatively unimpressive optimiser should have no problem running optimally.

Row storage should not be a concern for individual row retrieval, which is fortunate as there isn't much you can do to control it anyway. For MySQL performance you should probably choose MyISAM over InnoDB as the storage engine, provided your definition of "optimal" doesn't include "most reliable".




回答2:


It's the job of the database to accurately store and retrieve the data. You describe what you want, it delivers it. If you want to control specifically how it goes about doing so then a database is not the answer.



来源:https://stackoverflow.com/questions/874755/ruby-on-rails-activerecord-binary-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!