How to use Postgresql's "real" (float4) type in Rails 7.0, instead of the "double precision"?

huangapple go评论74阅读模式
英文:

How to use Postgresql's "real" (float4) type in Rails 7.0, instead of the "double precision"?

问题

我有一个连接到Postgres数据库的Rails 7.0应用程序。

我有几百万行的表,每行存储超过10个列作为浮点类型。

Rails中存储带有小数的数字的默认方式是浮点类型,它对应于Postgres中的float8类型(也称为双精度),这意味着存储为此类型的每个值都是8字节的数据。

通过告诉Rails告诉Postgres使用float4(real)而不是float8,我可以节省很多空间。

基本上将数据库中最大表的大小减少一半。

唯一的问题是我真的不知道如何做,也似乎找不到任何线索。

有人试过这样做吗?

如果是这样的话,我接受关于迁移本身的任何建议,因为我还需要将现有条目切换为float4。

最好!

英文:

I've got a Rails 7.0 app connected to a Postgres Database.

I've got tables with several millions of rows, and each row storing more than 10 columns as float types.

The default way of storing numbers with decimals in Rails is the float type, which corresponds to the float8 type in Postgres (also known as double precision), meaning each value stored as this type is 8bytes of data.

I could save a lot of space by telling Rails, to tell Postgres, to use float4 (real) instead of float8.

Basically cutting in half the size of the biggest table of my database.

The only thing is that i really don't know how to and i don't seem to find any clue about it.

Has someone ever tried to do this ?

Also if that's the case, i take any recommendation regarding the migration itself as i need to switch the existing entries to float4 as well.

Best!

答案1

得分: 1

通过对迁移进行调整,找到了答案。

只需将浮点类型的数字更改为4,就可以实现如下所示:

  def change
    add_column :my_table, :my_column, :float4
  end

在通过 psql 进行检查时,这将得到一个“real”列。

英文:

Found the answer by messing around with migrations.

It's as simple as adding a 4 to the float type like so:

  def change
    add_column :my_table, :my_column, :float4
  end

This results in a 'real' column when checking through psql.

huangapple
  • 本文由 发表于 2023年8月8日 22:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定