網頁

顯示具有 PostgreSQL 標籤的文章。 顯示所有文章
顯示具有 PostgreSQL 標籤的文章。 顯示所有文章

2013年3月10日

Efficient Use of PostgreSQL Indexes

Origin: Efficient Use of PostgreSQL Indexes

There are many types of indexes in Postgres, as well as different ways to use them. In this article we give an overview of the types of indexes available, and explain different ways of using and maintaining the most common index type: B-Trees.

Index Types

Postgres supports many different index types:
  • B-Tree is the default that you get when you do CREATE INDEX. The B stands for Balanced, and the idea is that the amount of data on both sides of the tree is roughly the same. Therefore the number of levels that must be traversed to find rows is always in the same ballpark. B-Tree indexes can be used for equality and range queries efficiently. They can operate against numeric, text or NULL values.
  • Hash Indexes are only useful for equality comparisons, but you pretty much never want to use them since they are not transaction safe, so the advantage over using a B-Tree is rather small.
  • Generalized Inverted Indexes (GIN) are useful when an index must map many values to one row, whereas B-Tree indexes are optimized for when a row has a single key value. GINs are good for indexing array values as well as for implementing full-text search.
  • Generalized Search Tree (GiST) indexes allow you to build general balanced tree structures, and can be used for operations beyond equality and range comparisons. They are used to index the geometric data types, as well as full-text search.
This article is about how to get the most out of default B-Tree indexes. For examples of GIN and GiST index usage, refer to the contrib packages.

2013年1月31日

PostgreSQL Backup

Origin: Restore One Table with psql from a pg_dump PostgreSQL Backup

Backing up and restoring PostgreSQL is fairly easy using pg_dump andpsql. One more complicated scenario I have run into is doing a complete database backup with pg_dump and at some point down the road needing to just split out one table and restore it. This can be a pain because of how the pg_dump organizes the .sql file it outputs. I have found the best way to do this is to use pg_dump to backup one table to understand the format of what is needed for a restore. Then search the .sql file that was output from the full pg_dump output and split out the necessary data to restore into one table. Below I provide some examples as well as syntax to use for backing up and/or restoring PostgreSQL using pg_dump and psql.

First lets look at the syntax required to backup a PostgreSQL database using pg_dump which I have done below. The first command will backup the entire database and output to a SQL file in the default format.

        pg_dump -U postgres dbname > data-dump.sql