SlideShare a Scribd company logo
Powering Rails 
Application with 
PostgreSQL 
Nidhi Sarvaiya
Who am I? 
➢ Developer at Icicle technologies from last 7 
years. 
➢ Ruby/Ruby on Rails developer since 2009 
➢ Official Handle @ice_on_rails 
➢ Personal Handle @sarvaiya_nidhi
What Are We Covering Today? 
➢ Why PostgreSQL 
➢ Advance Inbuilt Data Types 
➢ UUID 
➢ Full Text Search 
➢ Indexes 
➢ Third Party Gems
Why PostgreSQL? 
➢ First stable version was 6.0 
released in 1996 
➢ Latest stable version 9.3.5 
➢ Fast and reliable 
➢ Free, community support
Rails 4 Handshakes with PostgreSQL 
➢ As of Rails 4, many 
PostgreSQL features 
are supported out of box 
by Active Record
Built In Data Types 
➢ JSON 
➢ Arrays 
➢ hstore 
➢ Range Types 
➢ PostGis 
➢ Network Types
JSON 
Scenario 
Storing different social media information in your Rails 
Application. 
Traditional Approach 
Each social media sites returns different type of information 
so we usually go for NoSQL database 
Alternative 
Store data in JSON format in PostgreSQL
JSON Implementation 
Migration 
create_table :socials do |t| 
t.json 'profile' 
end 
Querying 
Social.first.profile['name'] => nidhi 
Social.select(“profile”) 
Sample Twitter JSON 
{ 
“username” :“sarvaiya_nidhi”, 
“name”:”nidhi”, 
“followers”:80 
}
Array 
Scenario 
Need to add multiple tags and ratings for Book 
Traditional Approach 
Add Separate table and map it with Book 
Alternative 
Add array field in Book table to map multiple tags and 
ratings
Array Implementation 
Migration 
create_table :books do |t| 
t.string :title 
t.string :tags, array: true 
end 
Querying 
Get Books with specific tag 
Book.where("’fiction’ = ANY (tags)") 
Get Books with all tags or multiple tags 
Book.where("’fiction’ = ALL (tags)") 
Book.where("tags @> ARRAY[?]::varchar[]", 
["fantasy", "fiction"]) 
Sampe Book Data 
Book 1 
<Book id: 1, title: "Brave New World", tags: 
["fantasy", "fiction"] > 
Book 2 
<Book id: 2, title: "The Hit", tags: 
["suspense", "thriller"] >
Hstore 
HStore is a key value store within Postgres. 
Scenario 
Need to apply different configuration for different clients 
Traditional Approach 
Maintain multiple entries in settings table by adding 
Key/Value details for each client 
Alternative 
Use Hstore to maintain all setting for client in single record
HStore Implementation 
Migration 
def self.up 
execute "CREATE EXTENSION hstore" 
end 
create_table :clients do |t| 
t.hstore 'settings' 
end 
Querying 
client = Client.first 
client.settings # => { "background-color" => "blue", 
“font-size”:”14px" } 
Get Specific value - client.settings["-background-color"] 
= "blue" 
Sample Hstore Data 
settings: { "background-color" => 
"blue", 
“font-size”:”14px" }
Range Types 
➢ daterange 
➢ int4range 
➢ int8range 
➢numrange 
➢ tsrange 
➢ tstzrange 
Let’s look at some of the them with example ->
Range Type - daterange 
Scenario 
Implement functionality of booking hotels room for specific 
duration 
Traditional Approach 
Need to maintain two different fields capturing start date 
and end date for booking duration 
Alternative 
Use daterange data type to store duration details
daterange Implementation 
Migration 
create_table :rooms do |t| 
t.daterange 'duration' 
end 
Querying 
All Events on a given date: 
Room.where("duration @> ?::date", 
Date.new(2014, 8, 14)) 
Sample Data 
Room1 
10/08/2014 - 14/08/2014 
Room1 
16/08/2014 - 21/08/2014
Range Type - int4range 
Scenario 
Implement functionality of capturing weather forecast 
Traditional Approach 
Need to maintain two different fields capturing high and low 
temperature details 
Alternative 
Use int4range data type to store temperature details
int4range Implementation 
Migration 
create_table :forecasts do |t| 
t.string :city 
t.int4range :hi_lo 
end 
Querying 
Forecast.create!(city: “mumbai”, hi_lo: 
29..32) 
Forecast.first.hi..lo => 29..32 
Sample Data 
Mumbai: 29..32 
Delhi: 31..24
PostGis 
➢ Geospatial extension to Postgres 
➢Support for Geographic objects 
➢New data types 
➢Functions to work with those data types 
➢ Spatial Index Support
Setup & Configuration 
➢ Installing Postgis 
➢ Add gems to support postgis with Active Record 
○ activerecord-postgis-adaptor 
○ rgeo 
➢ Add postgis adaptor in database.yml 
Reference 
http://daniel-azuma.com/articles/georails
Postgis Data Types 
➢ geometry - Any geometric type 
➢ point - Point data 
➢ line_string - LineString data 
➢ polygon - Polygon data 
➢ geometry_collection - Any collection type 
➢ multi_point - A collection of Points 
➢ multi_line_string - A collection of LineStrings 
➢ multi_polygon - A collection of Polygons
Network DataType 
➢ PostgreSQL comes with column types exclusively for IPv4, IPv6, 
and MAC addresses. 
➢ Active Record datatypes - inet, cidr and macaddre 
Migration 
create_table :network_addresses do |t| 
t.inet :inet_address 
t.cidr :cidr_address 
t.macaddr :mac_address 
end
UUID (Universally Unique Identifier) 
➢ Most of the applications now have API, so use UUID rather than 
integer for the ids 
➢ The uuid column type represents a universally unique identifier 
(UUID), a 128-bit value that is generated by an algorithm that 
makes it highly unlikely that the same value can be generated 
twice. 
➢ Sharding would be easier. Even re-merging all the data into a 
single database, if that's something you need at some point.
UUID ImplementaTion 
Enabling UUID Support 
def change 
enable_extension 'uuid-ossp' 
end 
Migration 
create_table :users, id: false do |t| 
t.primary_key :id, :uuid 
end 
or 
create_table :revisions do |t| 
t.column :identifier, :uuid 
end
Full Text Search 
➢ Since PostgreSQL 8.3 
➢ TSVECTOR to represent text data 
➢ TSQUERY to represent search predicates 
➢ Use pg_search gem for Rails application
Indexes Support in PostgreSQL 
➢B-Tree Indexes 
○ Unique Index 
○ Sorted Index 
○ Partial Indexes 
➢ Functional Indexes 
➢ Multi Column Indexes 
➢ GIST & GIN indexes
Gems 
➢ Full Text Search Gem 
○ pg_search - https://github.com/Casecommons/pg_search 
➢Database Insight 
○ pghero - https://github.com/ankane/pghero 
➢ Postgres Extensions 
○ postgres_ext - https://github.com/dockyard/postgres_ext
References 
http://edgeguides.rubyonrails.org/active_record 
_postgresql.html 
http://www.informit.com/articles/article.aspx?p= 
2220311&seqNum=13
THANK 
YOU

More Related Content

What's hot (20)

PPTX
Apache Cassandra Lunch #70: Basics of Apache Cassandra
Anant Corporation
 
PPT
2011 mongo FR - scaling with mongodb
antoinegirbal
 
PPT
Handle 08
Tony Hammond
 
PPTX
Data Binding in Grails
TO THE NEW | Technology
 
PPTX
Probabilistic Data Structures (Edmonton Data Science Meetup, March 2018)
Kyle Davis
 
PPTX
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
Olga Lavrentieva
 
PPTX
GAAD Database presentation
Md. Tariqul Islam
 
PPTX
Qtp training session II
Aisha Mazhar
 
PDF
What’s new in Alluxio 2: from seamless operations to structured data management
Alluxio, Inc.
 
PDF
MongoDB World 2016: The Best IoT Analytics with MongoDB
MongoDB
 
PDF
Mongodb in-anger-boston-rb-2011
bostonrb
 
PPTX
Need for Time series Database
Pramit Choudhary
 
PPT
ADO.net control
Paneliya Prince
 
PPTX
ElasticSearch Basics
Amresh Singh
 
PPTX
Time Series Data in a Time Series World
MapR Technologies
 
ODP
Elastic Search
NexThoughts Technologies
 
PPT
Whirlwind tour of Hadoop and HIve
Edward Capriolo
 
PPTX
How to leverage MongoDB for Big Data Analysis and Operations with MongoDB's A...
Gianfranco Palumbo
 
PDF
Trivadis TechEvent 2016 Polybase challenges Hive relational access to non-rel...
Trivadis
 
PDF
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
leifwalsh
 
Apache Cassandra Lunch #70: Basics of Apache Cassandra
Anant Corporation
 
2011 mongo FR - scaling with mongodb
antoinegirbal
 
Handle 08
Tony Hammond
 
Data Binding in Grails
TO THE NEW | Technology
 
Probabilistic Data Structures (Edmonton Data Science Meetup, March 2018)
Kyle Davis
 
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
Olga Lavrentieva
 
GAAD Database presentation
Md. Tariqul Islam
 
Qtp training session II
Aisha Mazhar
 
What’s new in Alluxio 2: from seamless operations to structured data management
Alluxio, Inc.
 
MongoDB World 2016: The Best IoT Analytics with MongoDB
MongoDB
 
Mongodb in-anger-boston-rb-2011
bostonrb
 
Need for Time series Database
Pramit Choudhary
 
ADO.net control
Paneliya Prince
 
ElasticSearch Basics
Amresh Singh
 
Time Series Data in a Time Series World
MapR Technologies
 
Elastic Search
NexThoughts Technologies
 
Whirlwind tour of Hadoop and HIve
Edward Capriolo
 
How to leverage MongoDB for Big Data Analysis and Operations with MongoDB's A...
Gianfranco Palumbo
 
Trivadis TechEvent 2016 Polybase challenges Hive relational access to non-rel...
Trivadis
 
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
leifwalsh
 

Similar to Powering Rails Application With PostgreSQL (20)

PDF
Rails israel 2013
Reuven Lerner
 
PDF
On Beyond (PostgreSQL) Data Types
Jonathan Katz
 
PDF
Heroku Postgres Cloud Database Webinar
Salesforce Developers
 
PDF
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
Андрей Новиков
 
PDF
Ruby on Rails & PostgreSQL - v2
John Ashmead
 
KEY
PostgreSQL
Reuven Lerner
 
PDF
PerlApp2Postgresql (2)
Jerome Eteve
 
PDF
Postgres the best tool you're already using
LiquidPlanner
 
PDF
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Alex Sharp
 
PDF
PGDay.Amsterdam 2018 - Bruce Momjian - Will postgres live forever
PGDay.Amsterdam
 
PPTX
PostgreSQL as NoSQL
Himanchali -
 
ODP
Introduction to PostgreSQL
Jim Mlodgenski
 
PDF
Postgres Vision 2018: Will Postgres Live Forever?
EDB
 
PDF
Gcp data engineer
Narendranath Reddy T
 
PPT
Heroku Waza 2013 Lessons Learned
Simon Bagreev
 
PDF
Ruby on Rails PostgreSQL: An Inclusive Guide On Set Up & Usage
rorbitssoftware
 
PPTX
Day 9 - PostgreSQL Application Architecture
Barry Jones
 
PDF
GCP Data Engineer cheatsheet
Guang Xu
 
PDF
Manchester Hadoop User Group: Cassandra Intro
Christopher Batey
 
PDF
Extensions on PostgreSQL
Alpaca
 
Rails israel 2013
Reuven Lerner
 
On Beyond (PostgreSQL) Data Types
Jonathan Katz
 
Heroku Postgres Cloud Database Webinar
Salesforce Developers
 
PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
Андрей Новиков
 
Ruby on Rails & PostgreSQL - v2
John Ashmead
 
PostgreSQL
Reuven Lerner
 
PerlApp2Postgresql (2)
Jerome Eteve
 
Postgres the best tool you're already using
LiquidPlanner
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Alex Sharp
 
PGDay.Amsterdam 2018 - Bruce Momjian - Will postgres live forever
PGDay.Amsterdam
 
PostgreSQL as NoSQL
Himanchali -
 
Introduction to PostgreSQL
Jim Mlodgenski
 
Postgres Vision 2018: Will Postgres Live Forever?
EDB
 
Gcp data engineer
Narendranath Reddy T
 
Heroku Waza 2013 Lessons Learned
Simon Bagreev
 
Ruby on Rails PostgreSQL: An Inclusive Guide On Set Up & Usage
rorbitssoftware
 
Day 9 - PostgreSQL Application Architecture
Barry Jones
 
GCP Data Engineer cheatsheet
Guang Xu
 
Manchester Hadoop User Group: Cassandra Intro
Christopher Batey
 
Extensions on PostgreSQL
Alpaca
 
Ad

Recently uploaded (20)

PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
Ad

Powering Rails Application With PostgreSQL

  • 1. Powering Rails Application with PostgreSQL Nidhi Sarvaiya
  • 2. Who am I? ➢ Developer at Icicle technologies from last 7 years. ➢ Ruby/Ruby on Rails developer since 2009 ➢ Official Handle @ice_on_rails ➢ Personal Handle @sarvaiya_nidhi
  • 3. What Are We Covering Today? ➢ Why PostgreSQL ➢ Advance Inbuilt Data Types ➢ UUID ➢ Full Text Search ➢ Indexes ➢ Third Party Gems
  • 4. Why PostgreSQL? ➢ First stable version was 6.0 released in 1996 ➢ Latest stable version 9.3.5 ➢ Fast and reliable ➢ Free, community support
  • 5. Rails 4 Handshakes with PostgreSQL ➢ As of Rails 4, many PostgreSQL features are supported out of box by Active Record
  • 6. Built In Data Types ➢ JSON ➢ Arrays ➢ hstore ➢ Range Types ➢ PostGis ➢ Network Types
  • 7. JSON Scenario Storing different social media information in your Rails Application. Traditional Approach Each social media sites returns different type of information so we usually go for NoSQL database Alternative Store data in JSON format in PostgreSQL
  • 8. JSON Implementation Migration create_table :socials do |t| t.json 'profile' end Querying Social.first.profile['name'] => nidhi Social.select(“profile”) Sample Twitter JSON { “username” :“sarvaiya_nidhi”, “name”:”nidhi”, “followers”:80 }
  • 9. Array Scenario Need to add multiple tags and ratings for Book Traditional Approach Add Separate table and map it with Book Alternative Add array field in Book table to map multiple tags and ratings
  • 10. Array Implementation Migration create_table :books do |t| t.string :title t.string :tags, array: true end Querying Get Books with specific tag Book.where("’fiction’ = ANY (tags)") Get Books with all tags or multiple tags Book.where("’fiction’ = ALL (tags)") Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"]) Sampe Book Data Book 1 <Book id: 1, title: "Brave New World", tags: ["fantasy", "fiction"] > Book 2 <Book id: 2, title: "The Hit", tags: ["suspense", "thriller"] >
  • 11. Hstore HStore is a key value store within Postgres. Scenario Need to apply different configuration for different clients Traditional Approach Maintain multiple entries in settings table by adding Key/Value details for each client Alternative Use Hstore to maintain all setting for client in single record
  • 12. HStore Implementation Migration def self.up execute "CREATE EXTENSION hstore" end create_table :clients do |t| t.hstore 'settings' end Querying client = Client.first client.settings # => { "background-color" => "blue", “font-size”:”14px" } Get Specific value - client.settings["-background-color"] = "blue" Sample Hstore Data settings: { "background-color" => "blue", “font-size”:”14px" }
  • 13. Range Types ➢ daterange ➢ int4range ➢ int8range ➢numrange ➢ tsrange ➢ tstzrange Let’s look at some of the them with example ->
  • 14. Range Type - daterange Scenario Implement functionality of booking hotels room for specific duration Traditional Approach Need to maintain two different fields capturing start date and end date for booking duration Alternative Use daterange data type to store duration details
  • 15. daterange Implementation Migration create_table :rooms do |t| t.daterange 'duration' end Querying All Events on a given date: Room.where("duration @> ?::date", Date.new(2014, 8, 14)) Sample Data Room1 10/08/2014 - 14/08/2014 Room1 16/08/2014 - 21/08/2014
  • 16. Range Type - int4range Scenario Implement functionality of capturing weather forecast Traditional Approach Need to maintain two different fields capturing high and low temperature details Alternative Use int4range data type to store temperature details
  • 17. int4range Implementation Migration create_table :forecasts do |t| t.string :city t.int4range :hi_lo end Querying Forecast.create!(city: “mumbai”, hi_lo: 29..32) Forecast.first.hi..lo => 29..32 Sample Data Mumbai: 29..32 Delhi: 31..24
  • 18. PostGis ➢ Geospatial extension to Postgres ➢Support for Geographic objects ➢New data types ➢Functions to work with those data types ➢ Spatial Index Support
  • 19. Setup & Configuration ➢ Installing Postgis ➢ Add gems to support postgis with Active Record ○ activerecord-postgis-adaptor ○ rgeo ➢ Add postgis adaptor in database.yml Reference http://daniel-azuma.com/articles/georails
  • 20. Postgis Data Types ➢ geometry - Any geometric type ➢ point - Point data ➢ line_string - LineString data ➢ polygon - Polygon data ➢ geometry_collection - Any collection type ➢ multi_point - A collection of Points ➢ multi_line_string - A collection of LineStrings ➢ multi_polygon - A collection of Polygons
  • 21. Network DataType ➢ PostgreSQL comes with column types exclusively for IPv4, IPv6, and MAC addresses. ➢ Active Record datatypes - inet, cidr and macaddre Migration create_table :network_addresses do |t| t.inet :inet_address t.cidr :cidr_address t.macaddr :mac_address end
  • 22. UUID (Universally Unique Identifier) ➢ Most of the applications now have API, so use UUID rather than integer for the ids ➢ The uuid column type represents a universally unique identifier (UUID), a 128-bit value that is generated by an algorithm that makes it highly unlikely that the same value can be generated twice. ➢ Sharding would be easier. Even re-merging all the data into a single database, if that's something you need at some point.
  • 23. UUID ImplementaTion Enabling UUID Support def change enable_extension 'uuid-ossp' end Migration create_table :users, id: false do |t| t.primary_key :id, :uuid end or create_table :revisions do |t| t.column :identifier, :uuid end
  • 24. Full Text Search ➢ Since PostgreSQL 8.3 ➢ TSVECTOR to represent text data ➢ TSQUERY to represent search predicates ➢ Use pg_search gem for Rails application
  • 25. Indexes Support in PostgreSQL ➢B-Tree Indexes ○ Unique Index ○ Sorted Index ○ Partial Indexes ➢ Functional Indexes ➢ Multi Column Indexes ➢ GIST & GIN indexes
  • 26. Gems ➢ Full Text Search Gem ○ pg_search - https://github.com/Casecommons/pg_search ➢Database Insight ○ pghero - https://github.com/ankane/pghero ➢ Postgres Extensions ○ postgres_ext - https://github.com/dockyard/postgres_ext
  • 27. References http://edgeguides.rubyonrails.org/active_record _postgresql.html http://www.informit.com/articles/article.aspx?p= 2220311&seqNum=13