Skip to content

Instantly share code, notes, and snippets.

@sputnikus
Last active December 29, 2015 15:29
Show Gist options
  • Save sputnikus/7690975 to your computer and use it in GitHub Desktop.
Save sputnikus/7690975 to your computer and use it in GitHub Desktop.
PyVo 28.11.2013 Lightning Eng version

hstore

Postgres

create extension hstore;

Key/value inside db column, keys and values are string-only

k => v
foo => bar, baz => whatever
"1-a" => "anything at all"

In database behaves like a dictionary, ability to do basic dictionary a set operations

GiST and GIN indexes for @>, ?, ?& a ?| operators; hash and btree for = - support for UNIQUE, GROUP BY, ORDER BY a DISTINCT

Python

In psycopg2 from version 2.3, enabling through

psycopg2.extras.register_hstore(conn_or_curs, globally=False, unicode=False, oid=None, array_oid=None)

hstore is converted from/to dictionary (allowing only string/unicode keys and values)

pip install django-hstore

In Django you can use it after installing extension as normal dictionary in your model

from django.db import models
from django_hstore import hstore

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

SQLAlchemy supports hstore from version 0.8 as postgresql.HSTORE type and postgresql.hstore() function

In SQLAlchemy ORM the best practice is to combine it with MutableDict (then it behaves like in Django)

data = Column(MutableDict.as_mutable(HSTORE))

MongoDB is dead. Long live Postgresql :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment