SlideShare a Scribd company logo
PostgreSQL для хипстеров
или почему ваш следующий проект должен быть на PostgreSQL
https://goo.gl/1uAZNi
Кто использует PostgreSQL
• по привычке
• по предложению заказчика
• на хайпе
Как мы выбираем БД?
• по привычке
• по предложению заказчика
• на хайпе
• Исходя из требований
Как мы выбираем БД?
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен быть на PostgreSQL
• 2003 — PG 8.2 - HSTORE
• 2012 — PG 9.2 - JSON
• 2013 — nested HSTORE (proposal) и
JSONB
• 2014 —PG 9.4 - JSONB, forget nested
hstore
• 2018? — SQL/JSON for 10.X or 11
JSON(B) в PostgreSQL
• select * from table where js->’field’ = 'foo' // field match
• where js @> '{"foo": "bar"}' // key-value match top-level
• where js ? 'b'// key exist
• {"a": 1} || {"b": 2} // {a: "1", b: "2"} - concat
• {a: "1", b: "2"} - "a" // {b: "2"} - delete key
JSON(B) в PostgreSQL
Найти "что-нибудь" красное
Table "public.js_test"
Column | Type | Modifiers
--------+---------+-----------
id | integer | not null
value | jsonb |
select * from js_test;
id |
----+-----------------------------------------------------------------------
1 | [1, "a", true, {"b": "c", "f": false}]
2 | {"a": "blue", "t": [{"color": "red", "width": 100}]}
3 | [{"color": "red", "width": 100}]
4 | {"color": "red", "width": 100}
5 | {"a": "blue", "t": [{"color": "red", "width": 100}], "color": "red"}
6 | {"a": "blue", "t": [{"color": "blue", "width": 100}], "color": "red"}
7 | {"a": "blue", "t": [{"color": "blue", "width": 100}], "colr": "red"}
8 | {"a": "blue", "t": [{"color": "green", "width": 100}]}
9 | {"color": "green", "value": "red", "width": 100}
(9 rows)
WITH RECURSIVE t(id, value) AS (
SELECT * FROM js_test
UNION ALL (
SELECT
t.id,

COALESCE(kv.value, e.value) AS value
FROM t
LEFT JOIN LATERAL jsonb_each(
CASE WHEN jsonb_typeof(t.value) ='object'
THEN t.value ELSE NULL END
) kv ON true
LEFT JOIN LATERAL jsonb_array_elements(
CASE WHEN jsonb_typeof(t.value) = 'array'
THEN t.value ELSE NULL END

) e ON true
WHERE
kv.value IS NOT NULL
OR e.value IS NOT NULL
)
)
SELECT js_test.* FROM (
SELECT id FROM t
WHERE
value @> '{"color":"red"}'
GROUP BY id

) x
JOIN js_test ON js_test.id = x.id;
Найти "что-нибудь" красное
Want some SQL?
SELECT * FROM js_test
WHERE
value @@ '*.color = "red"';
JSQuery
https://github.com/postgrespro/jsquery
• Новый тип данных jsonpath
• Функции для конструирования JSON
• Функции для выполнения запросов к JSON-полям
SQL / JSON (SQL-2016)
SELECT * FROM js_test 

WHERE 

JSON_EXISTS(value, '$.**.color ? (@ == "red")');
JSON - агрегация
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен быть на PostgreSQL
JSON-агрегация
SELECT * FROM users 

LEFT JOIN comments ON comments.user_id = users.id
users.id users.name comments.id comments.text comments.user_id comments.created_at
1 alice 1 hello 1 31.12.2017 23:59:50
1 alice 2 Happy NY! 1 01.01.2018 00:00:10
2 bob 3 You too! 2 01.01.2018 00:00:50
JSON-агрегация
select 

users.*, json_agg(comments.*) as comments

from users
left join comments on comments.user_id = users.id
group by users.id
users.id users.name comments
1 alice [

{ id: 1, text: "hello", created_at: "31.12.2017 23:59:50" }, 

{ id: 2, text: "Happy NY!", created_at: "01.01.2018 00:00:10"}

]
2 bob [{ id: 3, text: "You too!", created_at: "01.01.2018 00:00:50"}]
JSON-агрегация
select 

users.*, json_agg(comments.* ORDER BY created_at DESC) as comments

from users
left join comments on comments.user_id = users.id
group by users.id
users.id users.name comments
1 alice [

{ id: 1, text: "hello", created_at: "31.12.2017 23:59:50" }, 

{ id: 2, text: "Happy NY!", created_at: "01.01.2018 00:00:10"}

]
2 bob [{ id: 3, text: "You too!", created_at: "01.01.2018 00:00:50"}]
Оконные функции
select * from events
id type source_id created_at
1 foo 1
2 bar 2
3 a 1
4 b 2
5 c 3
6 d 1
7 e 1
Последние два события по каждому source_id?
Оконные функции
SELECT ROW_NUMBER() OVER (PARTITION by source_id) as row_number, * from events
row_number id type source_id created_at
1 7 e 1
2 6 d 1
3 3 a 1
4 1 foo 1
1 4 b 2
2 2 bar 2
1 5 c 3
Последние два события по каждому source_id?
Оконные функции
WITH events_cte AS (
SELECT
row_number() OVER (PARTITION by source_id) AS row_number, *
FROM events
) SELECT * FROM events_cte WHERE row_number <= 2
row_nunmber id type source_id created_at
1 7 e 1
2 6 d 1
1 4 b 2
2 2 bar 2
1 5 c 3
Оконные функции
• Все агрегирующие функции
• row_number, rank, dense_rank, percent_rank, cum_dist
• ntile(n)
• lag(value), lead(value)
• first_value, last_value, nth_value
• Много процессов
• Много серверов
Advisory locking
Advisory locking
1.Start transaction
2.pg_try_advisory_lock?
3.if success - start_operation()
4.else abort transaction
5.commit transaction -> release lock
1. Start transaction
2. pg_try_advisory_lock?
3. if success - start_operation()
4. else abort transaction
5. commit transaction -> release lock
process 1 process n…
Foreign Data Wrappers
• csv
• json
• mysql / postgres / oracle
• mongo
• elastic
• rest api
• whatever *
Foreign Data Wrappers
• MongoDB 3.2 now powered by PostgreSQL
• https://www.linkedin.com/pulse/mongodb-32-now-powered-
postgresql-john-de-goes/
Last but not least
• materialized view
• full text search
• pl/v8
• listen / notify
• native partitioning
• PostGIS
• where created_at <= NOW() - interval '5 weeks 2 hours 12
minutes'
• RDS / Aurora
node_modules
• MassiveJS - https://github.com/dmfay/massive-js
• MQL - https://github.com/marpple/MQL



const posts = await QUERY `SELECT * FROM posts WHERE id = ${id}`
• Postgraphile - https://www.graphile.org/postgraphile/
Links
• https://postgresweekly.com
• https://dbweekly.com
• https://github.com/dhamaniasad/awesome-postgres
• https://nodeweekly.com
Статистика переходов
Вопросы?
Спасибо!
Ad

Recommended

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
(ThoughtWorks Away Day 2009) one or two things you may not know about typesys...
Phil Calçado
 
Finch + Finagle OAuth2
Finch + Finagle OAuth2
Vladimir Kostyukov
 
Introduction to JQ
Introduction to JQ
Knoldus Inc.
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)
Yeshwanth Kumar
 
jq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
LogeekNightUkraine
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
Paulo Morgado
 
Async Microservices with Twitter's Finagle
Async Microservices with Twitter's Finagle
Vladimir Kostyukov
 
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
Stas Rivkin
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk
 
Rx.NET, from the inside out - Codemotion 2018
Rx.NET, from the inside out - Codemotion 2018
Stas Rivkin
 
Advanced JavaScript
Advanced JavaScript
Mahmoud Tolba
 
Type Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Introduction of ES2015
Introduction of ES2015
Nakajima Shigeru
 
Letswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 
サイ本 文
サイ本 文
Takashi Takizawa
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Paulo Silveira
 
C++ programs
C++ programs
Mukund Gandrakota
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
MongoDB
MongoDB
hyun soomyung
 
Reactive, component 그리고 angular2
Reactive, component 그리고 angular2
Jeado Ko
 
Testing (eng)
Testing (eng)
Derrick Chao
 
All I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросов
CodeFest
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
Ontico
 

More Related Content

What's hot (20)

NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
Paulo Morgado
 
Async Microservices with Twitter's Finagle
Async Microservices with Twitter's Finagle
Vladimir Kostyukov
 
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
Stas Rivkin
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk
 
Rx.NET, from the inside out - Codemotion 2018
Rx.NET, from the inside out - Codemotion 2018
Stas Rivkin
 
Advanced JavaScript
Advanced JavaScript
Mahmoud Tolba
 
Type Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Introduction of ES2015
Introduction of ES2015
Nakajima Shigeru
 
Letswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 
サイ本 文
サイ本 文
Takashi Takizawa
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Paulo Silveira
 
C++ programs
C++ programs
Mukund Gandrakota
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
MongoDB
MongoDB
hyun soomyung
 
Reactive, component 그리고 angular2
Reactive, component 그리고 angular2
Jeado Ko
 
Testing (eng)
Testing (eng)
Derrick Chao
 
All I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
Paulo Morgado
 
Async Microservices with Twitter's Finagle
Async Microservices with Twitter's Finagle
Vladimir Kostyukov
 
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
(Rx).NET' way of async programming (.NET summit 2017 Belarus)
Stas Rivkin
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk
 
Rx.NET, from the inside out - Codemotion 2018
Rx.NET, from the inside out - Codemotion 2018
Stas Rivkin
 
Type Driven Development with TypeScript
Type Driven Development with TypeScript
Garth Gilmour
 
Letswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Justjava 2007 Arquitetura Java EE Paulo Silveira, Phillip Calçado
Paulo Silveira
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
Reactive, component 그리고 angular2
Reactive, component 그리고 angular2
Jeado Ko
 
All I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
Noritada Shimizu
 

Similar to NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен быть на PostgreSQL (20)

NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросов
CodeFest
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
Ontico
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Ontico
 
Oh, that ubiquitous JSON !
Oh, that ubiquitous JSON !
Alexander Korotkov
 
Angular2 for Beginners
Angular2 for Beginners
Oswald Campesato
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
Mongoskin - Guilin
Mongoskin - Guilin
Jackson Tian
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Jonathan Katz
 
PostgreSQLからMongoDBへ
PostgreSQLからMongoDBへ
Basuke Suzuki
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
Roberto Franchini
 
Structure on a freeform world
Structure on a freeform world
Ikai (藍奕凱) Lan
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
Kevin Hazzard
 
Python postgre sql a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
PostgreSQL 9.4 JSON Types and Operators
PostgreSQL 9.4 JSON Types and Operators
Nicholas Kiraly
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformation
Lars Marius Garshol
 
greenDAO
greenDAO
Mu Chun Wang
 
Angular Weekend
Angular Weekend
Troy Miles
 
Postgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journey
Nicola Moretto
 
Json at work overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
Boulder Java User's Group
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Sages
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросов
CodeFest
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
Ontico
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Ontico
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
Mongoskin - Guilin
Mongoskin - Guilin
Jackson Tian
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Jonathan Katz
 
PostgreSQLからMongoDBへ
PostgreSQLからMongoDBへ
Basuke Suzuki
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
Roberto Franchini
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
Kevin Hazzard
 
Python postgre sql a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
 
PostgreSQL 9.4 JSON Types and Operators
PostgreSQL 9.4 JSON Types and Operators
Nicholas Kiraly
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformation
Lars Marius Garshol
 
Angular Weekend
Angular Weekend
Troy Miles
 
Postgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journey
Nicola Moretto
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Sages
 
Ad

Recently uploaded (20)

From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Ad

NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен быть на PostgreSQL

  • 1. PostgreSQL для хипстеров или почему ваш следующий проект должен быть на PostgreSQL https://goo.gl/1uAZNi
  • 3. • по привычке • по предложению заказчика • на хайпе Как мы выбираем БД?
  • 4. • по привычке • по предложению заказчика • на хайпе • Исходя из требований Как мы выбираем БД?
  • 6. • 2003 — PG 8.2 - HSTORE • 2012 — PG 9.2 - JSON • 2013 — nested HSTORE (proposal) и JSONB • 2014 —PG 9.4 - JSONB, forget nested hstore • 2018? — SQL/JSON for 10.X or 11 JSON(B) в PostgreSQL
  • 7. • select * from table where js->’field’ = 'foo' // field match • where js @> '{"foo": "bar"}' // key-value match top-level • where js ? 'b'// key exist • {"a": 1} || {"b": 2} // {a: "1", b: "2"} - concat • {a: "1", b: "2"} - "a" // {b: "2"} - delete key JSON(B) в PostgreSQL
  • 8. Найти "что-нибудь" красное Table "public.js_test" Column | Type | Modifiers --------+---------+----------- id | integer | not null value | jsonb | select * from js_test; id | ----+----------------------------------------------------------------------- 1 | [1, "a", true, {"b": "c", "f": false}] 2 | {"a": "blue", "t": [{"color": "red", "width": 100}]} 3 | [{"color": "red", "width": 100}] 4 | {"color": "red", "width": 100} 5 | {"a": "blue", "t": [{"color": "red", "width": 100}], "color": "red"} 6 | {"a": "blue", "t": [{"color": "blue", "width": 100}], "color": "red"} 7 | {"a": "blue", "t": [{"color": "blue", "width": 100}], "colr": "red"} 8 | {"a": "blue", "t": [{"color": "green", "width": 100}]} 9 | {"color": "green", "value": "red", "width": 100} (9 rows)
  • 9. WITH RECURSIVE t(id, value) AS ( SELECT * FROM js_test UNION ALL ( SELECT t.id,
 COALESCE(kv.value, e.value) AS value FROM t LEFT JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(t.value) ='object' THEN t.value ELSE NULL END ) kv ON true LEFT JOIN LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(t.value) = 'array' THEN t.value ELSE NULL END
 ) e ON true WHERE kv.value IS NOT NULL OR e.value IS NOT NULL ) ) SELECT js_test.* FROM ( SELECT id FROM t WHERE value @> '{"color":"red"}' GROUP BY id
 ) x JOIN js_test ON js_test.id = x.id; Найти "что-нибудь" красное
  • 11. SELECT * FROM js_test WHERE value @@ '*.color = "red"'; JSQuery https://github.com/postgrespro/jsquery
  • 12. • Новый тип данных jsonpath • Функции для конструирования JSON • Функции для выполнения запросов к JSON-полям SQL / JSON (SQL-2016) SELECT * FROM js_test 
 WHERE 
 JSON_EXISTS(value, '$.**.color ? (@ == "red")');
  • 15. JSON-агрегация SELECT * FROM users 
 LEFT JOIN comments ON comments.user_id = users.id users.id users.name comments.id comments.text comments.user_id comments.created_at 1 alice 1 hello 1 31.12.2017 23:59:50 1 alice 2 Happy NY! 1 01.01.2018 00:00:10 2 bob 3 You too! 2 01.01.2018 00:00:50
  • 16. JSON-агрегация select 
 users.*, json_agg(comments.*) as comments
 from users left join comments on comments.user_id = users.id group by users.id users.id users.name comments 1 alice [
 { id: 1, text: "hello", created_at: "31.12.2017 23:59:50" }, 
 { id: 2, text: "Happy NY!", created_at: "01.01.2018 00:00:10"}
 ] 2 bob [{ id: 3, text: "You too!", created_at: "01.01.2018 00:00:50"}]
  • 17. JSON-агрегация select 
 users.*, json_agg(comments.* ORDER BY created_at DESC) as comments
 from users left join comments on comments.user_id = users.id group by users.id users.id users.name comments 1 alice [
 { id: 1, text: "hello", created_at: "31.12.2017 23:59:50" }, 
 { id: 2, text: "Happy NY!", created_at: "01.01.2018 00:00:10"}
 ] 2 bob [{ id: 3, text: "You too!", created_at: "01.01.2018 00:00:50"}]
  • 18. Оконные функции select * from events id type source_id created_at 1 foo 1 2 bar 2 3 a 1 4 b 2 5 c 3 6 d 1 7 e 1 Последние два события по каждому source_id?
  • 19. Оконные функции SELECT ROW_NUMBER() OVER (PARTITION by source_id) as row_number, * from events row_number id type source_id created_at 1 7 e 1 2 6 d 1 3 3 a 1 4 1 foo 1 1 4 b 2 2 2 bar 2 1 5 c 3 Последние два события по каждому source_id?
  • 20. Оконные функции WITH events_cte AS ( SELECT row_number() OVER (PARTITION by source_id) AS row_number, * FROM events ) SELECT * FROM events_cte WHERE row_number <= 2 row_nunmber id type source_id created_at 1 7 e 1 2 6 d 1 1 4 b 2 2 2 bar 2 1 5 c 3
  • 21. Оконные функции • Все агрегирующие функции • row_number, rank, dense_rank, percent_rank, cum_dist • ntile(n) • lag(value), lead(value) • first_value, last_value, nth_value
  • 22. • Много процессов • Много серверов Advisory locking
  • 23. Advisory locking 1.Start transaction 2.pg_try_advisory_lock? 3.if success - start_operation() 4.else abort transaction 5.commit transaction -> release lock 1. Start transaction 2. pg_try_advisory_lock? 3. if success - start_operation() 4. else abort transaction 5. commit transaction -> release lock process 1 process n…
  • 24. Foreign Data Wrappers • csv • json • mysql / postgres / oracle • mongo • elastic • rest api • whatever *
  • 25. Foreign Data Wrappers • MongoDB 3.2 now powered by PostgreSQL • https://www.linkedin.com/pulse/mongodb-32-now-powered- postgresql-john-de-goes/
  • 26. Last but not least • materialized view • full text search • pl/v8 • listen / notify • native partitioning • PostGIS • where created_at <= NOW() - interval '5 weeks 2 hours 12 minutes' • RDS / Aurora
  • 27. node_modules • MassiveJS - https://github.com/dmfay/massive-js • MQL - https://github.com/marpple/MQL
 
 const posts = await QUERY `SELECT * FROM posts WHERE id = ${id}` • Postgraphile - https://www.graphile.org/postgraphile/
  • 28. Links • https://postgresweekly.com • https://dbweekly.com • https://github.com/dhamaniasad/awesome-postgres • https://nodeweekly.com