PostgreSQL

Postgres Hstore

PostgreSQL hstore refers to an extension that provides access to key-value storage for the PostgreSQL database. It allows us to store the key-value pairs similar to the Redis database within a single PostgreSQL column. This is an incredible feature when storing the data with dynamic attributes or properties in a particular row.

In this tutorial, we will walk you throw how to enable and use the hstore values in PostgreSQL in simple steps.

Enable the Hstore Extension

To store the hstore values in PostgreSQL, we need to enable the hstore extension. In PostgreSQL 9.1 and above, the hstore extension is installed by default; hence, you only need to activate it.

To enable the hstore extension in PostgreSQL, run the following query:

CREATE EXTENSION IF NOT EXISTS hstore;

Once we enable the extension, we can create a table with an hstore column and start storing the key-value pairs.

Store the Hstore Data

The following example demonstrates how we can use the CREATE TABLE clause in PostgreSQL to create a table with an hstore column:

CREATE TABLE my_table (
    id SERIAL PRIMARY KEY,
    data hstore
);

In the given example, we create a table called my_table with two columns: id and data. The data column has an hstore data type which allows us to store the key-value pairs.

As demonstrated, we can insert the data into the table with a set of key-value pairs which are enclosed in single quotes.

INSERTINTO my_table (data) VALUES ('"key1"=>"value1", "key2"=>"value2"');

Finally, to retreive the rows from the table, we can run the following query:

SELECT * FROM my_table;

This should return the stored values as demonstrated in the following:

id |                data
----+------------------------------------
  1 | "key1"=>"value1", "key2"=>"value2"
  2 | "key1"=>"value1", "key2"=>"value2"
(2 rows)

Query a Specific Key

If we have an hstore column, we can use the -> operator to query the value of a specific key from the column.

For example:

SELECT data->'key1' AS value FROM my_table;

In the given example, we use the -> operator to retrieve the value that is associated with the “key1” key from the data column.

The result includes a column named “value” that contains the corresponding value.

Output:

value
--------
 value1
 value1
(2 rows)

Alternatively, the #> operator can access the nested keys within the hstore column.

An example is as follows:

SELECT data#>'{key1}' AS value FROM my_table;

The given example requires a nested key-value pair.

Add a Key-Value Pair

In PostgreSQL, we can quickly and easily add a new key-value pair to an existing hstore column using the “||” operator. This allows us to concatenate a new key-value pair with an existing hstore value.

An example is as follows:

UPDATE my_table SET data = data || '"new_key"=>"new_value"' WHERE id = 1;

This should add a new key and value pairs.

Run the following select statement on the table:

SELECT * FROM my_table;

The given query returns the following:

id |                            data
----+------------------------------------------------------------
  2 | "key1"=>"value1", "key2"=>"value2"
  1 | "key1"=>"value1", "key2"=>"value2", "new_key"=>"new_value"
(2 rows)

Check a Specific Key

PostgreSQL allows us to check if a specific key exists on the hstore column using the “?” operator in the WHERE clause.

An example is as follows:

SELECT data ? 'key1' AS key_exists FROM my_table;

Output:

key_exists
------------
 t
 t
(2 rows)

In the given example, we use the “?” operator to check if the “key1” key exists in the data column of the my_table table.

The result includes a column named key_exists that indicates whether the key is present (true) or not (false).

Check the Key-Value Pair

We can also check for a key-value pair using the “@>” operator. An example is as follows:

SELECT * FROM my_table WHERE data @> '"key1"=>"value1"';

Fetch All Keys

To get all the keys for a given hstore column, we can use the akeys() function as shown in the following example:

select akeys(data) from my_table;

Resulting Output:

        akeys
---------------------
 {key1,key2}
 {key1,key2,new_key}
(2 rows)

You can also use the skeys() column to fetch the keys as a set value.

select skeys(data) from my_table;

Output:

  skeys
---------
 key1
 key2
 key1
 key2
 new_key
(5 rows)

Fetch All Values

As you can guess, we can use the avals() function to fetch all the values that are stored in a given hstore column as shown in the following example query:

select avals(data) from my_table;

Output:

           avals
---------------------------
 {value1,value2}
 {value1,value2,new_value}
(2 rows)

To fetch the values as a set, use the svals() function.

Convert Hstore to Json

We can convert the data that is stored in an hstore column into JSON using the hstore_to_json() function.

An example is as follows:

select hstore_to_json(data) from my_table;

The given query should convert the provided hstore to a JSON data as follows:

                        hstore_to_json
--------------------------------------------------------------
 {"key1": "value1", "key2": "value2"}
 {"key1": "value1", "key2": "value2", "new_key": "new_value"}
(2 rows)

Conclusion

We covered the hstore extension in PostgreSQL. We explored how we can enable the hstore extensions, how to create the PostgreSQL hstore columns, access the values, modify the hstore values, and more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list