SlideShare a Scribd company logo
1 of 80
Download to read offline
G!"#$ b%&!#' ()%
      D*+#$! ORM
,"-"(+("!#. w"() P/($r%.
 @0r+"$1%r.("%#.
PSA: Macs

  Postgres.app
Why Postgres
 “Its the emacs of databases”
 http://www.craigkerstiens.com/2012/04/30/why-postgres/
https://speakerdeck.com/craigkerstiens/postgres-demystified
TLDR
         Datatypes                Fast Column Addition
    Conditional Indexes               Listen/Notify
     Transactional DDL              Table Inheritance
  Foreign Data Wrappers     Per Transaction sync replication
Concurrent Index Creation          Window functions
        Extensions                  NoSQL inside SQL
Common Table Expressions               Momentum
Limitations?
Django attempts to support as many features
as possible on all database backends. However,
not all database backends are alike, and we’ve
had to make design decisions on which
features to support and which assumptions
we can make safely.
D+(+(2%.
__________
< Postgres >
 ----------
         ^__^
         (oo)_______
          (__)        )/
               ||----w |
               ||     ||
DatatypesUUID
                      date                   boolean
timestamptzarray             intervalinteger
                    bigint
   smallint line            XML enum
                                           char
                         money
         serial bytea                  point     float
 inet               polygon numeric            circle
        cidr  varchar      tsquery timetz
path           time     text
       macaddr                timestamp box
                   tsvector
DatatypesUUID
                      date                   boolean
timestamptzarray             intervalinteger
                    bigint
   smallint line            XML enum
                                           char
                         money
         serial bytea                  point     float
 inet               polygon numeric            circle
        cidr  varchar      tsquery timetz
path           time     text
       macaddr                timestamp box
                   tsvector
DatatypesUUID
                      date                   boolean
timestamptzarray             intervalinteger
                    bigint
   smallint line            XML enum
                                           char
                         money
         serial bytea                  point     float
 inet               polygon numeric            circle
        cidr  varchar      tsquery timetz
path           time     text
       macaddr                timestamp box
                   tsvector
DatatypesUUID
                      date                   boolean
timestamptzarray             intervalinteger
                    bigint
   smallint line            XML enum
                                           char
                         money
         serial bytea                  point     float
 inet                polygon numeric           circle
        cidr  varchar      tsquery timetz
path           time     text
       macaddr                timestamp box
                   tsvector
_______
< SQLite >
 ---------
          ^__^
         (oo)_______
           (__)        )/
                ||----w |
                ||     ||
Datatypes
              null
                     integer
text
                     real

       blob
DatatypesUUID
                      date                   boolean
timestamptzarray             intervalinteger
                    bigint
   smallint line            XML enum
                                           char
                         money
         serial bytea                  point     float
 inet               polygon numeric            circle
        cidr  varchar      tsquery timetz
path           time     text
       macaddr                timestamp box
                   tsvector
I#'3%.
________
< Postgres >
 ----------
          ^__^
         (oo)_______
           (__)        )/
                ||----w |
                ||     ||
Indexes
Multiple Types
   B-Tree, Gin, Gist, KNN, SP-Gist



CREATE INDEX CONCURRENTLY
_____
< MySQL >
 -------
         ^__^
         (oo)_______
          (__)        )/
               ||----w |
               ||     ||
Indexes
They exist
Digging In
Arrays
CREATE TABLE item (
    id serial NOT NULL,
    name varchar (255),
    tags varchar(255) [],
    created_at timestamp
);
Arrays
CREATE TABLE item (
    id serial NOT NULL,
    name varchar (255),
    tags varchar(255) [],
    created_at timestamp
);
Arrays
INSERT INTO item
VALUES (1, 'Django Pony',
'{“Programming”,”Animal”}', now());

INSERT INTO item
VALUES (2, 'Ruby Gem',
'{“Programming”,”Jewelry”}', now());
Arrays
INSERT INTO item
VALUES (1, 'Django Pony',
'{“Programming”,”Animal”}', now());

INSERT INTO item
VALUES (2, 'Ruby Gem',
'{“Programming”,”Jewelry”}', now());
Django
pip install djorm-ext-pgarray
pip install djorm-ext-expressions

models.py:


from djorm_pgarray.fields import ArrayField
from djorm_expressions.models import ExpressionManager

class Item(models.Model):
    name = models.CharField(max_length=255)
    tags = ArrayField(dbtype="varchar(255)")
    created_at = models.DateTimeField(auto_now=True)
Django
pip install djorm-ext-pgarray
pip install djorm-ext-expressions

models.py:


from djorm_pgarray.fields import ArrayField
from djorm_expressions.models import ExpressionManager

class Item(models.Model):
    name = models.CharField(max_length=255)
    tags = ArrayField(dbtype="varchar(255)")
    created_at = models.DateTimeField(auto_now=True)
Django
i = Item(
    name='Django Pony',
    tags=['Programming','Animal'])
i.save()

qs = Item.objects.where(
    SqlExpression("tags", "@>", ['programming'])
)
Django
i = Item(
    name='Django Pony',
    tags=['Programming','Animal'])
i.save()

qs = Item.objects.where(
    SqlExpression("tags", "@>", ['programming'])
)
Extensions
 dblink          hstore                  trigram
                           uuid-ossp               pgstattuple
        citext
                          pgcrypto
  isn             ltree           fuzzystrmatch
          cube                            dict_int
                    earthdistance
unaccent                                             dict_xsyn
                            btree_gist
            tablefunc                      pgrowlocks
NoSQL in your SQL
NoSQL in your SQL
CREATE EXTENSION hstore;
CREATE TABLE item (
    id integer NOT NULL,
    name varchar(255),
    data hstore,
);
NoSQL in your SQL
CREATE EXTENSION hstore;
CREATE TABLE item (
    id integer NOT NULL,
    name varchar(255),
    data hstore,
);
NoSQL in your SQL
INSERT INTO items
VALUES (
 1,
 'Pony',
 'rating => "4.0", color => “Pink”',
);
NoSQL in your SQL
INSERT INTO items
VALUES (
 1,
 'Pony',
 'rating => "4.0", color => “Pink”',
);
Django
pip install django-hstore

from django.db import models
from django_hstore import hstore

class Item(models.Model):
    name = models.CharField(max_length=250)
    data = hstore.DictionaryField(db_index=True)
    objects = hstore.Manager()

    def __unicode__(self):
        return self.name
Django
pip install django-hstore

from django.db import models
from django_hstore import hstore

class Item(models.Model):
    name = models.CharField(max_length=250)
    data = hstore.DictionaryField(db_index=True)
    objects = hstore.Manager()

    def __unicode__(self):
        return self.name
Django
Item.objects.create(
    name='Django Pony',
    data={'rating': '5'})

Item.objects.create(
    name='Pony',
    data={'color': 'pink', 'rating': '4'})
Django
Item.objects.create(
    name='Django Pony',
    data={'rating': '5'})

Item.objects.create(
    name='Pony',
    data={'color': 'pink', 'rating': '4'})
Django
colored_ponies =
  Product.objects.filter(data__contains='color')
print colored_ponies[0].data['color']

favorite_ponies =
  Product.objects.filter(data__contains={'rating': '5'})
print colored_ponies[0]
Django
colored_ponies =
  Product.objects.filter(data__contains='color')
print colored_ponies[0].data['color']

favorite_ponies =
  Product.objects.filter(data__contains={'rating': '5'})
print colored_ponies[0]
JSON
JSON

w/ PLV8
Q4%4%"#$
Pub/Sub?
Postgres a
great Queue
Postgres a
  great Queue

Not With Polling
Trunk
pip install celery trunk

psql < sql/*.sql
celery worker -A tasks --loglevel=info

ipython -i tasks.py
>>> add.delay(2, 2)
Trunk
pip install celery trunk

psql < sql/*.sql
celery worker -A tasks --loglevel=info

ipython -i tasks.py
>>> add.delay(2, 2)
Trunk
from celery import Celery

celery = Celery('tasks')
celery.config_from_object({
    'BROKER_URL': 'trunk.transport.Transport://
localhost/trunk',
})

@celery.task
def add(x, y):
    return x + y
Trunk
from celery import Celery

celery = Celery('tasks')
celery.config_from_object({
    'BROKER_URL': 'trunk.transport.Transport://
localhost/trunk',
})

@celery.task
def add(x, y):
    return x + y
T3( S%+r0)
Searching Text
Searching Text
 Lucene
          Elastic Search

Sphinx
                    Solr
Searching Text
 Lucene
             Elastic Search

Sphinx
          Postgres
                       Solr
Full Text Search
CREATE TABLE posts (
   id serial,
   title varchar(255),
   content text,
   tags varchar(255)[],
   post_text tsvector
);

CREATE INDEX posttext_gin ON
posts USING GIN(post_text);

CREATE TRIGGER update_posttext
BEFORE INSERT OR UPDATE ON posts
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(
  ‘PostText’,‘english’,title, content, tags);
Full Text Search
CREATE TABLE posts (
   id serial,
   title varchar(255),
   content text,
   tags varchar(255)[],
   post_text tsvector
);

CREATE INDEX posttext_gin ON
posts USING GIN(post_text);

CREATE TRIGGER update_posttext
BEFORE INSERT OR UPDATE ON posts
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(
  ‘PostText’,‘english’,title, content, tags);
Django
from djorm_pgfulltext.models import SearchManager
from djorm_pgfulltext.fields import VectorField
from django.db import models

class Posts(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    search_index = VectorField()

    objects = SearchManager(
        fields = ('title', 'content'),
        config = 'pg_catalog.english',
        search_field = 'search_index',
        auto_update_search_field = True
    )
Django
from djorm_pgfulltext.models import SearchManager
from djorm_pgfulltext.fields import VectorField
from django.db import models

class Posts(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

    search_index = VectorField()

    objects = SearchManager(
        fields = ('title', 'content'),
        config = 'pg_catalog.english',
        search_field = 'search_index',
        auto_update_search_field = True
    )
Django
Post.objects.search("documentation & about")


Post.objects.search("about | documentation")
Django
Post.objects.search("documentation & about")


Post.objects.search("about | documentation")
I#'3%.
Indexes
B-Tree
Generalized Inverted Index (GIN)
Generalized Search Tree (GIST)
K Nearest Neighbors (KNN)
Space Partitioned GIST (SP-GIST)
Indexes
Which do I use?
Indexes
B-Tree
Generalized Inverted Index (GIN)
Generalized Search Tree (GIST)
K Nearest Neighbors (KNN)
Space Partitioned GIST (SP-GIST)
Generalized Inverted Index (GIN)
 Use with multiple values in 1 column
 Array/hStore
Generalized Search Tree (GIST)
 Full text search
 Shapes
 PostGIS
Indexes
B-Tree
Generalized Inverted Index (GIN)
Generalized Search Tree (GIST)
K Nearest Neighbors (KNN)
Space Partitioned GIST (SP-GIST)
G%!Sp+("+,
GeoDjango
                http://geodjango.org/

https://speakerdeck.com/pyconslides/location-location-
                      location
O#% M!r%
Connections
Connections
django-postgrespool
djorm-ext-pool
django-db-pool
django-postgrespool
import dj_database_url
import django_postgrespool

DATABASE = { 'default': dj_database_url.config() }
DATABASES['default']['ENGINE'] = 'django_postgrespool'

SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.postgresql_psycopg2'
}
django-postgrespool
import dj_database_url
import django_postgrespool

DATABASE = { 'default': dj_database_url.config() }
DATABASES['default']['ENGINE'] = 'django_postgrespool'

SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.postgresql_psycopg2'
}
Limitations?
Django attempts to support as many features
as possible on all database backends. However,
not all database backends are alike, and we’ve
had to make design decisions on which
features to support and which assumptions
we can make safely.
P/($r%.

Its great
D*+#$! ORM

Its not so bad
5+#1.!

More Related Content

What's hot

Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesJonathan Katz
 
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)Jamey Hanson
 
On Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesOn Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesJonathan Katz
 
Flexible Indexing with Postgres
Flexible Indexing with PostgresFlexible Indexing with Postgres
Flexible Indexing with PostgresEDB
 
ElasticSearch AJUG 2013
ElasticSearch AJUG 2013ElasticSearch AJUG 2013
ElasticSearch AJUG 2013Roy Russo
 
Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014Holden Karau
 
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovPostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovNikolay Samokhvalov
 
Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015StampedeCon
 
아파트 정보를 이용한 ELK stack 활용 - 오근문
아파트 정보를 이용한 ELK stack 활용 - 오근문아파트 정보를 이용한 ELK stack 활용 - 오근문
아파트 정보를 이용한 ELK stack 활용 - 오근문NAVER D2
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовNoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовCodeFest
 
Developing and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWDeveloping and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWJonathan Katz
 
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...Ontico
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Holden Karau
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Michaël Figuière
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Cassandra Data Modeling - Practical Considerations @ Netflix
Cassandra Data Modeling - Practical Considerations @ NetflixCassandra Data Modeling - Practical Considerations @ Netflix
Cassandra Data Modeling - Practical Considerations @ Netflixnkorla1share
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationMongoDB
 

What's hot (20)

Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
 
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
 
On Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesOn Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data Types
 
Flexible Indexing with Postgres
Flexible Indexing with PostgresFlexible Indexing with Postgres
Flexible Indexing with Postgres
 
ElasticSearch AJUG 2013
ElasticSearch AJUG 2013ElasticSearch AJUG 2013
ElasticSearch AJUG 2013
 
Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014
 
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovPostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
 
Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015
 
아파트 정보를 이용한 ELK stack 활용 - 오근문
아파트 정보를 이용한 ELK stack 활용 - 오근문아파트 정보를 이용한 ELK stack 활용 - 오근문
아파트 정보를 이용한 ELK stack 활용 - 오근문
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
NoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросовNoSQL для PostgreSQL: Jsquery — язык запросов
NoSQL для PostgreSQL: Jsquery — язык запросов
 
Developing and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWDeveloping and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDW
 
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Elasticsearch speed is key
Elasticsearch speed is keyElasticsearch speed is key
Elasticsearch speed is key
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Cassandra Data Modeling - Practical Considerations @ Netflix
Cassandra Data Modeling - Practical Considerations @ NetflixCassandra Data Modeling - Practical Considerations @ Netflix
Cassandra Data Modeling - Practical Considerations @ Netflix
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 

Similar to Going beyond Django ORM limitations with Postgres

The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31Mahmoud Samir Fayed
 
Heroku Postgres Cloud Database Webinar
Heroku Postgres Cloud Database WebinarHeroku Postgres Cloud Database Webinar
Heroku Postgres Cloud Database WebinarSalesforce Developers
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David SzakallasDatabricks
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text ProcessingRodrigo Senra
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수용 최
 
MongoSF - mongodb @ foursquare
MongoSF - mongodb @ foursquareMongoSF - mongodb @ foursquare
MongoSF - mongodb @ foursquarejorgeortiz85
 

Similar to Going beyond Django ORM limitations with Postgres (20)

Postgres demystified
Postgres demystifiedPostgres demystified
Postgres demystified
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 
Heroku Postgres Cloud Database Webinar
Heroku Postgres Cloud Database WebinarHeroku Postgres Cloud Database Webinar
Heroku Postgres Cloud Database Webinar
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted Malaska
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
SVGo workshop
SVGo workshopSVGo workshop
SVGo workshop
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
CAVE Overview
CAVE OverviewCAVE Overview
CAVE Overview
 
MongoSF - mongodb @ foursquare
MongoSF - mongodb @ foursquareMongoSF - mongodb @ foursquare
MongoSF - mongodb @ foursquare
 

Recently uploaded

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Going beyond Django ORM limitations with Postgres

  • 1. G!"#$ b%&!#' ()% D*+#$! ORM ,"-"(+("!#. w"() P/($r%. @0r+"$1%r.("%#.
  • 2. PSA: Macs Postgres.app
  • 3. Why Postgres “Its the emacs of databases” http://www.craigkerstiens.com/2012/04/30/why-postgres/ https://speakerdeck.com/craigkerstiens/postgres-demystified
  • 4. TLDR Datatypes Fast Column Addition Conditional Indexes Listen/Notify Transactional DDL Table Inheritance Foreign Data Wrappers Per Transaction sync replication Concurrent Index Creation Window functions Extensions NoSQL inside SQL Common Table Expressions Momentum
  • 5. Limitations? Django attempts to support as many features as possible on all database backends. However, not all database backends are alike, and we’ve had to make design decisions on which features to support and which assumptions we can make safely.
  • 7. __________ < Postgres > ---------- ^__^ (oo)_______ (__) )/ ||----w | || ||
  • 8. DatatypesUUID date boolean timestamptzarray intervalinteger bigint smallint line XML enum char money serial bytea point float inet polygon numeric circle cidr varchar tsquery timetz path time text macaddr timestamp box tsvector
  • 9. DatatypesUUID date boolean timestamptzarray intervalinteger bigint smallint line XML enum char money serial bytea point float inet polygon numeric circle cidr varchar tsquery timetz path time text macaddr timestamp box tsvector
  • 10. DatatypesUUID date boolean timestamptzarray intervalinteger bigint smallint line XML enum char money serial bytea point float inet polygon numeric circle cidr varchar tsquery timetz path time text macaddr timestamp box tsvector
  • 11. DatatypesUUID date boolean timestamptzarray intervalinteger bigint smallint line XML enum char money serial bytea point float inet polygon numeric circle cidr varchar tsquery timetz path time text macaddr timestamp box tsvector
  • 12. _______ < SQLite > --------- ^__^ (oo)_______ (__) )/ ||----w | || ||
  • 13. Datatypes null integer text real blob
  • 14. DatatypesUUID date boolean timestamptzarray intervalinteger bigint smallint line XML enum char money serial bytea point float inet polygon numeric circle cidr varchar tsquery timetz path time text macaddr timestamp box tsvector
  • 16. ________ < Postgres > ---------- ^__^ (oo)_______ (__) )/ ||----w | || ||
  • 17. Indexes Multiple Types B-Tree, Gin, Gist, KNN, SP-Gist CREATE INDEX CONCURRENTLY
  • 18. _____ < MySQL > ------- ^__^ (oo)_______ (__) )/ ||----w | || ||
  • 21. Arrays CREATE TABLE item ( id serial NOT NULL, name varchar (255), tags varchar(255) [], created_at timestamp );
  • 22. Arrays CREATE TABLE item ( id serial NOT NULL, name varchar (255), tags varchar(255) [], created_at timestamp );
  • 23. Arrays INSERT INTO item VALUES (1, 'Django Pony', '{“Programming”,”Animal”}', now()); INSERT INTO item VALUES (2, 'Ruby Gem', '{“Programming”,”Jewelry”}', now());
  • 24. Arrays INSERT INTO item VALUES (1, 'Django Pony', '{“Programming”,”Animal”}', now()); INSERT INTO item VALUES (2, 'Ruby Gem', '{“Programming”,”Jewelry”}', now());
  • 25. Django pip install djorm-ext-pgarray pip install djorm-ext-expressions models.py: from djorm_pgarray.fields import ArrayField from djorm_expressions.models import ExpressionManager class Item(models.Model): name = models.CharField(max_length=255) tags = ArrayField(dbtype="varchar(255)") created_at = models.DateTimeField(auto_now=True)
  • 26. Django pip install djorm-ext-pgarray pip install djorm-ext-expressions models.py: from djorm_pgarray.fields import ArrayField from djorm_expressions.models import ExpressionManager class Item(models.Model): name = models.CharField(max_length=255) tags = ArrayField(dbtype="varchar(255)") created_at = models.DateTimeField(auto_now=True)
  • 27. Django i = Item( name='Django Pony', tags=['Programming','Animal']) i.save() qs = Item.objects.where( SqlExpression("tags", "@>", ['programming']) )
  • 28. Django i = Item( name='Django Pony', tags=['Programming','Animal']) i.save() qs = Item.objects.where( SqlExpression("tags", "@>", ['programming']) )
  • 29. Extensions dblink hstore trigram uuid-ossp pgstattuple citext pgcrypto isn ltree fuzzystrmatch cube dict_int earthdistance unaccent dict_xsyn btree_gist tablefunc pgrowlocks
  • 31. NoSQL in your SQL CREATE EXTENSION hstore; CREATE TABLE item ( id integer NOT NULL, name varchar(255), data hstore, );
  • 32. NoSQL in your SQL CREATE EXTENSION hstore; CREATE TABLE item ( id integer NOT NULL, name varchar(255), data hstore, );
  • 33. NoSQL in your SQL INSERT INTO items VALUES ( 1, 'Pony', 'rating => "4.0", color => “Pink”', );
  • 34. NoSQL in your SQL INSERT INTO items VALUES ( 1, 'Pony', 'rating => "4.0", color => “Pink”', );
  • 35. Django pip install django-hstore from django.db import models from django_hstore import hstore class Item(models.Model): name = models.CharField(max_length=250) data = hstore.DictionaryField(db_index=True) objects = hstore.Manager() def __unicode__(self): return self.name
  • 36. Django pip install django-hstore from django.db import models from django_hstore import hstore class Item(models.Model): name = models.CharField(max_length=250) data = hstore.DictionaryField(db_index=True) objects = hstore.Manager() def __unicode__(self): return self.name
  • 37. Django Item.objects.create( name='Django Pony', data={'rating': '5'}) Item.objects.create( name='Pony', data={'color': 'pink', 'rating': '4'})
  • 38. Django Item.objects.create( name='Django Pony', data={'rating': '5'}) Item.objects.create( name='Pony', data={'color': 'pink', 'rating': '4'})
  • 39. Django colored_ponies = Product.objects.filter(data__contains='color') print colored_ponies[0].data['color'] favorite_ponies = Product.objects.filter(data__contains={'rating': '5'}) print colored_ponies[0]
  • 40. Django colored_ponies = Product.objects.filter(data__contains='color') print colored_ponies[0].data['color'] favorite_ponies = Product.objects.filter(data__contains={'rating': '5'}) print colored_ponies[0]
  • 41.
  • 42. JSON
  • 45.
  • 48. Postgres a great Queue Not With Polling
  • 49. Trunk pip install celery trunk psql < sql/*.sql celery worker -A tasks --loglevel=info ipython -i tasks.py >>> add.delay(2, 2)
  • 50. Trunk pip install celery trunk psql < sql/*.sql celery worker -A tasks --loglevel=info ipython -i tasks.py >>> add.delay(2, 2)
  • 51. Trunk from celery import Celery celery = Celery('tasks') celery.config_from_object({ 'BROKER_URL': 'trunk.transport.Transport:// localhost/trunk', }) @celery.task def add(x, y): return x + y
  • 52. Trunk from celery import Celery celery = Celery('tasks') celery.config_from_object({ 'BROKER_URL': 'trunk.transport.Transport:// localhost/trunk', }) @celery.task def add(x, y): return x + y
  • 55. Searching Text Lucene Elastic Search Sphinx Solr
  • 56. Searching Text Lucene Elastic Search Sphinx Postgres Solr
  • 57. Full Text Search CREATE TABLE posts ( id serial, title varchar(255), content text, tags varchar(255)[], post_text tsvector ); CREATE INDEX posttext_gin ON posts USING GIN(post_text); CREATE TRIGGER update_posttext BEFORE INSERT OR UPDATE ON posts FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( ‘PostText’,‘english’,title, content, tags);
  • 58. Full Text Search CREATE TABLE posts ( id serial, title varchar(255), content text, tags varchar(255)[], post_text tsvector ); CREATE INDEX posttext_gin ON posts USING GIN(post_text); CREATE TRIGGER update_posttext BEFORE INSERT OR UPDATE ON posts FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( ‘PostText’,‘english’,title, content, tags);
  • 59. Django from djorm_pgfulltext.models import SearchManager from djorm_pgfulltext.fields import VectorField from django.db import models class Posts(models.Model): title = models.CharField(max_length=200) content = models.TextField() search_index = VectorField() objects = SearchManager( fields = ('title', 'content'), config = 'pg_catalog.english', search_field = 'search_index', auto_update_search_field = True )
  • 60. Django from djorm_pgfulltext.models import SearchManager from djorm_pgfulltext.fields import VectorField from django.db import models class Posts(models.Model): title = models.CharField(max_length=200) content = models.TextField() search_index = VectorField() objects = SearchManager( fields = ('title', 'content'), config = 'pg_catalog.english', search_field = 'search_index', auto_update_search_field = True )
  • 64. Indexes B-Tree Generalized Inverted Index (GIN) Generalized Search Tree (GIST) K Nearest Neighbors (KNN) Space Partitioned GIST (SP-GIST)
  • 66. Indexes B-Tree Generalized Inverted Index (GIN) Generalized Search Tree (GIST) K Nearest Neighbors (KNN) Space Partitioned GIST (SP-GIST)
  • 67. Generalized Inverted Index (GIN) Use with multiple values in 1 column Array/hStore
  • 68. Generalized Search Tree (GIST) Full text search Shapes PostGIS
  • 69. Indexes B-Tree Generalized Inverted Index (GIN) Generalized Search Tree (GIST) K Nearest Neighbors (KNN) Space Partitioned GIST (SP-GIST)
  • 71. GeoDjango http://geodjango.org/ https://speakerdeck.com/pyconslides/location-location- location
  • 75. django-postgrespool import dj_database_url import django_postgrespool DATABASE = { 'default': dj_database_url.config() } DATABASES['default']['ENGINE'] = 'django_postgrespool' SOUTH_DATABASE_ADAPTERS = { 'default': 'south.db.postgresql_psycopg2' }
  • 76. django-postgrespool import dj_database_url import django_postgrespool DATABASE = { 'default': dj_database_url.config() } DATABASES['default']['ENGINE'] = 'django_postgrespool' SOUTH_DATABASE_ADAPTERS = { 'default': 'south.db.postgresql_psycopg2' }
  • 77. Limitations? Django attempts to support as many features as possible on all database backends. However, not all database backends are alike, and we’ve had to make design decisions on which features to support and which assumptions we can make safely.