PostgreSQL可以直接存储二进制的文件。例如图片、文档,视频等。

其他数据库系统也是可以存数组的,不过还是最终以字符串的形式存的,取出和读取都是用程序来序列化。假如不用字符串存,那就得多准备一张表,例如,一篇文章要记录什么人收藏过。就得多一张表,每次判断用户是否收藏过,就得查那张表,而数据以冗余的方式存在数据中,就是把user_id存进去一个字段,这样就大大方便了。PostgreSQL默认就支持数据的存取,还支持对数据的各种操作,比如查找等。

  1. create_table :books do |t|
  2. t.string 'title'
  3. t.string 'tags', array: true
  4. t.integer 'ratings', array: true
  5. end
  6. add_index :books, :tags, using: 'gin'
  7. add_index :books, :ratings, using: 'gin'
  8. # app/models/book.rb
  9. class Book < ActiveRecord::Base
  10. end
  11. # Usage
  12. Book.create title: "Brave New World",
  13. tags: ["fantasy", "fiction"],
  14. ratings: [4, 5]
  15. ## Books for a single tag
  16. Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])
  17. ## Books with 3 or more ratings
  18. Book.where("array_length(ratings, 1) >= 3")

PostgreSQL还支持对array的各种操作,给了详细的解释。

比如,把数组进行类似join的操作。

  1. Book.select("title, array_to_string(tags, '_')")
  2. SELECT title, array_to_string(tags, '_') FROM "books";
  3. title | array_to_string
  4. -----------------+-----------------
  5. Brave New World | fantasy_fiction
  6. (1 row)

Hstore是PostgreSQL的一个扩展,它能够存放键值对,比如,json,hash等半结构化数据。一般的数据库系统是没有这种功能,而这种需求是很常见的,所以说,PostgreSQL是最具Nosql特性的。只要前端通过js提交一些hash或json,或者通过form提交一些数据,就能直接以json等形式存到数据库中。例如,一个用户有1个,0个,或多个联系人,如果以关系型数据库来存的话,只能多建立一张表来存,然后用has_many,belongs_to来处理。而Hstore就是以字段的形式来存,这就很方便了。

像array一样,Hstore也是支持很多操作的,官方文档hstore给了详细的描述。

  1. rails365_dev=# SELECT "profiles".settings -> 'color' FROM "profiles"
  2. ;
  3. ?column?
  4. ----------
  5. yellow
  6. blue
  7. (2 rows)
  8. ?column?
  9. ----------
  10. t
  11. t
  12. (2 rows)
  13. rails365_dev=# SELECT hstore_to_json("profiles".settings) FROM "profiles"
  14. ;
  15. hstore_to_json
  16. ---------------------------------------------------------------
  17. {"color": "yellow", "resolution": "1280x1024"}
  18. {"color": "blue", "resolution": "[\"800x600\", \"750x670\"]"}
  19. (2 rows)
  20. rails365_dev=# SELECT "profiles".settings -> 'color' FROM "profiles"
  21. where settings->'color' = 'yellow';
  22. ?column?
  23. ----------
  24. yellow
  25. (1 row)

更多详细只要查看官文文档就好了。

关于Hstore有一个gem是,这个gem提供了很多关于Hstore的查询方法。

using-postgres-hstore-rails4这篇文章介绍了Hstore的用法。

完结。