Logical replication is a feature in PostgreSQL that enables the replication of individual database objects or a subset of data from one PostgreSQL database to a
Logical replication is a feature in PostgreSQL that enables the replication of individual database objects or a subset of data from one PostgreSQL database to another.
With logical replication, you can selectively replicate specific tables, databases, or even specific rows based on predefined replication rules. This provides more flexibility compared to physical replication, where the entire database cluster is replicated. It allows you to design custom replication topologies and replicate only the data that is necessary for your use case.
We will show you how to use logical replication to replicate data from one PostgreSQL database to another.
Now, we can set logical replication between source database and target database.
Prepare test data
We need to create a table named test with a column named embedding of type vector(10) in source database and target database. Then we create an index on the embedding column of the test table in source database and target database. Finally, we insert data into the source database.
We create an index on the embedding column of the test table in source database and target database. The index type is flat, it is a brute force algorithm. We choose vector_l2_ops squared Euclidean distance to measure the distance between vectors. Another index type and distance function can be found in here.
To simplify the process of setting up logical replication between two PostgreSQL databases, we will use pg-easy-replicate.
We use pg-easy-replicate to set up logical replication between source database and target database.
# get the network name$ docker network ls | grep pg
8631dd77129b pg_regress_localnet bridge local# get source and target container ip$ docker inspect <container_id> | grep IP
$ docker run -e SOURCE_DB_URL="postgres://postgres:password@<source_db_ip>:5432/postgres" -e TARGET_DB_URL="postgres://postgres:password@<target_db_ip>:5432/postgres" -it --rm --network=<network> shayonj/pg_easy_replicate:latest pg_easy_replicate config_check
/usr/bin/pg_dump
✅ Config is looking good.
Bootstrap
Every sync will need to be bootstrapped before you can set up the sync between two databases. Bootstrap creates a new super user to perform the orchestration required during the rest of the process. It also creates some internal metadata tables for record keeping.
Once the bootstrap is complete, you can start the sync. Starting the sync sets up the publication, subscription and performs other minor housekeeping things.
Now we can query the target database to get the nearest neighbor of a vector in the embedding column of the test table. The result is the same as the source database.