HStore is a key value store
within Postgres. We can use it similar to how you would
use a dictionary within another language, though it’s specific to a column on a row. The
HStore extension is available in the package
postgresql-contrib
, we need to
install this package in order to enable HStore extension in the Postgres schema.
Installation
Command to install postgresql-contrib package in Ubuntu
ljain@machine:~$ sudo apt-get install postgresql-contrib
Enabling HStore on Database in the postgres user
postgres@machine:~$ CREATE EXTENSION hstore;
Creating An HStore Column
To create a field in a table with the hstore data type simply use hstore as the column type
CREATE TABLE test ( id serial PRIMARY KEY, name varchar, attributes hstore);
Data Insertion / Retrival
To insert data you would include it all within single quotes as you would for a text field. The difference with hstore is some extra structure so it knows how to create the dictionary:Inserting Data
INSERT INTO test (name attribute) VALUES ( 'Programming Scala', 'author => "Dean Wampler",
pages => 464, category => Programming' );
Retrieving Data
SELECT name, attribute->'pages' as pages FROM test WHERE attribute->'category' = 'Programming';
Post a Comment
Post a Comment