15
Rails 4 + Postgres = NoSQL Yoni Weisbrod @yoniweisbrod 500tech hstore 500tech

Rails 4 + Postgres = NoSQL - Rails Israel 2014

Embed Size (px)

Citation preview

Page 1: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Rails 4 + Postgres = NoSQL

Yoni Weisbrod@yoniweisbrod

500tech

hstore

500tech

Page 2: Rails 4 + Postgres = NoSQL - Rails Israel 2014

User

photo_url :string

name :string

verified? :bool

email :string

Yo

Twitter

LinkedIn

@yoniweisbrod

Page 3: Rails 4 + Postgres = NoSQL - Rails Israel 2014

User

photo_url :string

name :string

verified? :bool

email :string

Yo

Twitter

LinkedInprofiles :hstore

@yoniweisbrod

Page 4: Rails 4 + Postgres = NoSQL - Rails Israel 2014

> u = User.first

> u.profiles = {yo: “yoni_w”, linked_in: “yweisbrod”}

Not just a Hash

@yoniweisbrod

Page 5: Rails 4 + Postgres = NoSQL - Rails Israel 2014

hstore

flexibility of NoSQL

integration with a relational database

no maintenance of an additional database

fully queryable

@yoniweisbrod

Page 6: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Enable hstore on your Postgres database

# db/migrate/20131220144913_enable_hstore.rb

def up

enable_extension “hstore"end

def down

disable_extension “hstore”

end

@yoniweisbrod

Page 7: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Add the hstore field to your table

# db/migrate/20131220145432_add_profiles_to_users.rb

def change

add_column :users, :profiles, :hstoreend

@yoniweisbrod

Page 8: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Add accessor methods for known keys

class User < ActiveRecord::Base

store_accessor :profiles, :yo, :linkedin

end

User.first.yo

@yoniweisbrod

Page 9: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Great Rails Integration

• Add validations for specific keys

• Add indexes to speed up queries

@yoniweisbrod

Page 10: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Gotchas

• All strings

• No nested hashes.

nested-hstore gem

hstore_accessor gem

@yoniweisbrod

Page 11: Rails 4 + Postgres = NoSQL - Rails Israel 2014

powerful query operands

@yoniweisbrod

Page 12: Rails 4 + Postgres = NoSQL - Rails Israel 2014

User.where(“profiles -> ‘yo’ = :name”, name: ‘yoni’)

Query the value of a key

@yoniweisbrod

Page 13: Rails 4 + Postgres = NoSQL - Rails Israel 2014

User.where(“profiles ?& ARRAY[‘yo’, ‘linked_in’]”)

User.where(“profiles ?| ARRAY[‘yo’, ‘linked_in’]”)

User.where(“profiles ? ‘yo’”)

Query the presence of a key

@yoniweisbrod

Page 14: Rails 4 + Postgres = NoSQL - Rails Israel 2014

User.where(“profiles @> :kv”, kv: “yo=>yoni_w”)

Query the presence of a key-value pair

@yoniweisbrod

Page 15: Rails 4 + Postgres = NoSQL - Rails Israel 2014

Rails 4 + Postgres = NoSQL

hstore

500tech

Yoni Weisbrod@yoniweisbrod

500tech