SlideShare a Scribd company logo
PostgreSQL’s Secret
NoSQL Superpowers
Amanda Gilmore
Postgres supports several
document data formats.
Formats
XML
hstore
json
jsonb
How do you choose?
Do you wrap a foreign database?
How do you choose?
Do you have a (fairly) standard object schema with weird objects?
How do you choose?
Are you worried about lock contention?
XML
http://www.postgresql.org/docs/9.5/static/functions-xml.html
Schema
CREATE TABLE xml_samples (
id bigserial PRIMARY KEY,
documents xml,
comments text
)
Create
INSERT INTO xml_samples (documents, comments) VALUES (
XMLPARSE( DOCUMENT $$<?xml version="1.0"?>
<catalog>
...
</catalog>$$)
, 'This is an entire XML document')
Create
--Alternatively, this inserts one node per row
INSERT INTO xml_samples (documents, comments) VALUES (
$$<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>$$
, 'one book per row, as an XML node')
Read
--Gets all titles in the table
SELECT xpath('//book/title', documents) FROM xml_samples
--Gets all info on a book by title
SELECT * FROM xml_samples WHERE (xpath('//book/title/text()'
, documents))[1]::text = 'Midnight Rain'::text
Update
Cannot do this natively.
hstore
http://www.postgresql.org/docs/9.5/static/hstore.html
Schema
CREATE EXTENSION hstore
CREATE TABLE hstore_samples (
id bigserial PRIMARY KEY,
documents hstore,
comments text
)
Create
INSERT INTO hstore_samples (documents, comments)
VALUES ('"active_resource"=>"true"
,"resource_name"=>"swimming-swiftly-1234"
,"resource_size_in_mb"=>"30"
,"resource_created_at"=>"2016-03-14 17:20:47.216862"'
, 'this is a straight up K/V hash')
Read
--hstores are strings under the hood and require casting
SELECT * from hstore_samples
WHERE (documents -> 'resource_size_in_mb')::int > 30
Read
--You can get all of the values for a certain key:
SELECT (documents -> 'resource_name')::text
FROM hstore_samples
--or convert the entire table to an hstore:
SELECT hstore(t) FROM hstore_samples AS t
Read
--Pulling multiple values from the document
SELECT (documents -> 'resource_name')::text
, (documents -> 'active_resource')::text
FROM hstore_samples
Update
--Cannot do this in place , hence the || operator
UPDATE hstore_samples
SET documents = documents || '"active_resource"=>"false"'::hstore
WHERE documents @> '"resource_name"=>"swimming-swiftly-1234"'::hstore
json & jsonb
http://www.postgresql.org/docs/9.5/static/datatype-json.html
Read
--get json object. Array element by index (int) or by key
(str)
->
--get json object *by text*
->>
--containment operator, used to get an object by path
@>
--checks for existence of a key
?
http://www.postgresql.org/docs/9.5/static/functions-json.html
Schema
CREATE TABLE json_samples (
id bigserial PRIMARY KEY,
text_json json,
binary_json jsonb,
notes text
)
Create
INSERT INTO json_samples (text_json, notes) VALUES (
'{
"minStartTimeNs": "1429828653617000000",
"maxEndTimeNs": "1429839639367000000",
"dataSourceId":
"derived:com.google.heart_rate.bpm:com.google.android.gms:merge_heart_rate_bpm"
}'
, 'This is in the text json field')
Read
--Can check top-level keys before querying:
SELECT jsonb_object_keys(binary_json) FROM json_samples
--Well formed JSON path:
['point'][0]['value'][0]['fpVal']
--And you can extract specific values from the document:
SELECT binary_json->'point'->0->'value'->0->'fpVal' FROM json_samples
--Can check if a given key is present:
SELECT * FROM json_samples WHERE text_json::jsonb ? 'dataSourceId'
SELECT * FROM json_samples WHERE binary_json ? 'dataSourceId'
--And can check if the value of the key matches something:
SELECT * FROM json_samples
WHERE binary_json ->> 'minStartTimeNs' = '1429828653617000000'
Read
Update
--Can update at top level:
UPDATE json_samples
SET binary_json = binary_json || '{"address": {
"streetAddress": "123 Test Street",
"city": "Oakland",
"state": "CA",
"postalCode": "94123"
} }'
WHERE binary_json ->> 'lastName' = 'Gilmore'
Update
--or use jsonb_set() to drill down the tree:
SELECT jsonb_set(binary_json::jsonb
, '{address, streetAddress}'
, '"456 Lorem Ipsum St"'::jsonb)
FROM json_samples
WHERE binary_json ->> 'lastName' = 'Gilmore'
tl;dr
xml Can query on xpath Can’t update
hstore Can index keys Text, less performant
json Richly nested data Text, less performant
jsonb Nested data, fast reads Higher cost writes
xml: http://www.postgresql.org/docs/9.5/static/functions-xml.html
hstore: http://www.postgresql.org/docs/9.5/static/hstore.html
json & jsonb: http://www.postgresql.org/docs/9.5/static/functions-json.html
Source for the xml sample: https://msdn.microsoft.com/en-
us/library/ms762271(v=vs.85).aspx
Sample code for this talk on GitHub:
https://github.com/mandagill/PGConfUS_2016_syntax_samples
Links & References
Links & References
Questions?
Thanks, y’all!
amanda@heroku.com
GitHub: mandagill

More Related Content

What's hot (20)

PDF
wtf is in Java/JDK/wtf7?
Scott Leberknight
 
PPT
Introduction to MongoDB
antoinegirbal
 
PPT
XML - State of the Art
Jakub Malý
 
DOC
Ex[1].3 php db connectivity
Mouli Chandira
 
PPTX
Cassandra 2.2 & 3.0
Victor Coustenoble
 
PPTX
MS SQL Database basic
wali1195189
 
PPTX
MUC - Moodle Universal Cache
Tim Hunt
 
PDF
Softshake - Offline applications
jeromevdl
 
PDF
MongoDB and RDBMS
francescapasha
 
PDF
Brief introduction of Slick
Knoldus Inc.
 
PPT
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
TXT
Threading
b290572
 
PDF
BITS: Introduction to relational databases and MySQL - SQL
BITS
 
PDF
Mongo db for C# Developers
Simon Elliston Ball
 
PDF
Mongo db for c# developers
Simon Elliston Ball
 
PPTX
Introduction to the new official C# Driver developed by 10gen
MongoDB
 
PDF
Building Go Web Apps
Mark
 
PPTX
19. CodeIgniter imagini in mysql
Razvan Raducanu, PhD
 
PDF
Productive Programming in Groovy
Ganesh Samarthyam
 
PDF
Cassandra rapid prototyping with achilles
Duyhai Doan
 
wtf is in Java/JDK/wtf7?
Scott Leberknight
 
Introduction to MongoDB
antoinegirbal
 
XML - State of the Art
Jakub Malý
 
Ex[1].3 php db connectivity
Mouli Chandira
 
Cassandra 2.2 & 3.0
Victor Coustenoble
 
MS SQL Database basic
wali1195189
 
MUC - Moodle Universal Cache
Tim Hunt
 
Softshake - Offline applications
jeromevdl
 
MongoDB and RDBMS
francescapasha
 
Brief introduction of Slick
Knoldus Inc.
 
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
Threading
b290572
 
BITS: Introduction to relational databases and MySQL - SQL
BITS
 
Mongo db for C# Developers
Simon Elliston Ball
 
Mongo db for c# developers
Simon Elliston Ball
 
Introduction to the new official C# Driver developed by 10gen
MongoDB
 
Building Go Web Apps
Mark
 
19. CodeIgniter imagini in mysql
Razvan Raducanu, PhD
 
Productive Programming in Groovy
Ganesh Samarthyam
 
Cassandra rapid prototyping with achilles
Duyhai Doan
 

Viewers also liked (20)

PPTX
Charlene Ygoña
michane710
 
PPTX
Wekerle CIHR Team - Trauma Profiles and Correlates Among Maltreated Adolesce...
Christine Wekerle
 
PDF
BOS-BOF MONTHLY REPORT -MARCH 2016
Bill Leverence
 
PDF
LESER-Safety-Valve-Compact-Performance-Extended-Catalog-EN
Leser UK
 
PPTX
Pearson y de Sperman
John Palencia
 
PPT
Educational Achievement among Child Welfare Youth: The Maltreatment and Adole...
Christine Wekerle
 
PDF
ComputerWorld Intervju
Ali Ahmad
 
PPT
Resiliency among Child Welfare Youth: Findings from The Maltreatment and Adol...
Christine Wekerle
 
PPTX
Wekerle CIHR Team - CAPHC - The Maltreatment and Adolescent Pathways (MAP) Re...
Christine Wekerle
 
PPT
Presentació pastors final
Escola el colomer BIR
 
DOCX
Mithran j cv21316
Mithran Joseph
 
PDF
Critical_Service_Catalog_EN
Leser UK
 
PPTX
Presentación1
John Palencia
 
PPT
CONSIDERATIONS FROM THE MALTREATMENT AND ADOLESCENT PATHWAYS (MAP) LONGITUDIN...
Christine Wekerle
 
PPT
The linkages among childhood maltreatment, adolescent mental health, and self...
Christine Wekerle
 
PDF
القانون الجنائي
ismail chibout
 
PPTX
SES Lighting Parking Garage LED Installation
Nelson A. Scott, CCM
 
PDF
Mid-Jersey Business March 2016
Evelyn Fairman
 
DOCX
Mithran J CV21316
Mithran Joseph
 
ODP
Dez illas máis bonitas
naomyvazquez
 
Charlene Ygoña
michane710
 
Wekerle CIHR Team - Trauma Profiles and Correlates Among Maltreated Adolesce...
Christine Wekerle
 
BOS-BOF MONTHLY REPORT -MARCH 2016
Bill Leverence
 
LESER-Safety-Valve-Compact-Performance-Extended-Catalog-EN
Leser UK
 
Pearson y de Sperman
John Palencia
 
Educational Achievement among Child Welfare Youth: The Maltreatment and Adole...
Christine Wekerle
 
ComputerWorld Intervju
Ali Ahmad
 
Resiliency among Child Welfare Youth: Findings from The Maltreatment and Adol...
Christine Wekerle
 
Wekerle CIHR Team - CAPHC - The Maltreatment and Adolescent Pathways (MAP) Re...
Christine Wekerle
 
Presentació pastors final
Escola el colomer BIR
 
Mithran j cv21316
Mithran Joseph
 
Critical_Service_Catalog_EN
Leser UK
 
Presentación1
John Palencia
 
CONSIDERATIONS FROM THE MALTREATMENT AND ADOLESCENT PATHWAYS (MAP) LONGITUDIN...
Christine Wekerle
 
The linkages among childhood maltreatment, adolescent mental health, and self...
Christine Wekerle
 
القانون الجنائي
ismail chibout
 
SES Lighting Parking Garage LED Installation
Nelson A. Scott, CCM
 
Mid-Jersey Business March 2016
Evelyn Fairman
 
Mithran J CV21316
Mithran Joseph
 
Dez illas máis bonitas
naomyvazquez
 
Ad

Similar to PostgreSQL's Secret NoSQL Superpowers (20)

PPT
Jquery 4
Manish Kumar Singh
 
PPTX
Open Source Search: An Analysis
Justin Finkelstein
 
PPTX
Taming that client side mess with Backbone.js
Jarod Ferguson
 
PPTX
Data and information about anatical subject
epfoportal69
 
PDF
XQuery Rocks
William Candillon
 
PPT
Jquery 2
Manish Kumar Singh
 
KEY
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
PDF
Xml & Java
Slim Ouertani
 
PPT
JavaScript JQUERY AJAX
Makarand Bhatambarekar
 
PPT
Propel sfugmd
iKlaus
 
PDF
Php (1)
pinalsadiwala
 
PDF
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
PDF
Understanding backbonejs
Nick Lee
 
PPTX
Miracle Open World 2011 - XML Index Strategies
Marco Gralike
 
PDF
Php summary
Michelle Darling
 
PPTX
Art of Javascript
Tarek Yehia
 
PDF
Struts database access
Abass Ndiaye
 
PPTX
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
PDF
Drupal & javascript
Almog Baku
 
PDF
jQuery and Rails: Best Friends Forever
stephskardal
 
Open Source Search: An Analysis
Justin Finkelstein
 
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Data and information about anatical subject
epfoportal69
 
XQuery Rocks
William Candillon
 
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
Xml & Java
Slim Ouertani
 
JavaScript JQUERY AJAX
Makarand Bhatambarekar
 
Propel sfugmd
iKlaus
 
Php (1)
pinalsadiwala
 
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
Understanding backbonejs
Nick Lee
 
Miracle Open World 2011 - XML Index Strategies
Marco Gralike
 
Php summary
Michelle Darling
 
Art of Javascript
Tarek Yehia
 
Struts database access
Abass Ndiaye
 
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
Drupal & javascript
Almog Baku
 
jQuery and Rails: Best Friends Forever
stephskardal
 
Ad

Recently uploaded (20)

PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Import Data Form Excel to Tally Services
Tally xperts
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 

PostgreSQL's Secret NoSQL Superpowers

Editor's Notes

  • #2: -Who am I? Why do I care? => We use a lot of rich data stores on my team and querying gets complicated. I rather wish I had these slides when I started working heavily on PG. -Don’t worry about photoing slides, SQL is in GitHub -Assume I’m talking about 9.5 unless otherwise stated
  • #4: Do you want to put all the data in PG and format some fields as documents? Do you want to wrap a NoSQL DB? Here are some questions to ask that may help you come to an answer...
  • #5: Use the data format that maps your foreign data source Mongo -> json Redis -> hstore
  • #6: If your information *generally* maps to an object, likely easier to stay in PG entirely. E.g. car rental
  • #7: Are you worried about lock contention? -> You might have a single json blob in a field, but that row is always going to be locked when you’re performing some operation on it
  • #8: Yeaaaaaah xpaths RSS feeds amirite?
  • #11: Hstore values *must be a string*
  • #13: Asynchronous information processing is a possible use case here. I.e., stashing the API payload as soon as I get it and then processing it later in-application, queued process, etc.
  • #14: Available since 9.1 Contrib module Supports indexing, YEAH
  • #15: Contrib module, need to CREATE EXTENSION
  • #16: This is a basic string, but adding it into an hstore formatted field gives you the extra function-y goodness INSERT is nice and straightforward
  • #17: PG: You could have a B-Tree expression index on the expression "(documents -> 'resource_created_at')::timestamptz" here, which would let you use a b-tree index for the > operator here (Something GIN cannot do). HGMNZ: GIN indexes' support for hstore means that you can index all fields in an hstore with one index, which is quite unique as far as database functionality goes.
  • #21: PostgreSQL allows only one character set encoding per database. It is therefore not possible for the JSON types to conform rigidly to the JSON specification unless the database encoding is UTF8. Check with SHOW SERVER_ENCODING; Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Straight json - only when manipulating data at the application layer All the shiny operators work with jsonb jsonb - Supports indexing! :D LOCKS ARE STILL ROW LEVEL.
  • #22: The ->> is important; if I am matching on ‘Gilmore’ text, I need the ->> instead of the ->
  • #25: This is where it gets fun. :) Can query more deeply nested objects
  • #26: These are for top-level keys
  • #29: Here I’m going to verbally specify that with higher cost writes for jsonb, they are more expensive but reads are cheaper (much like you’d see for a normal column index in any case)