This tutorial shows you how to deploy a PostgreSQL vector database cluster on Google Kubernetes Engine (GKE).
PostgreSQL comes with a range of modules and extensions that extend the database's functionality. In this tutorial, you install the pgvector extension on an existing PostgreSQL cluster deployed to GKE. The Pgvector extension lets you store vectors in the database tables by adding vector types to PostgreSQL. Pgvector also provides similarity searches by running common SQL queries.
We simplify the PGvector extension deployment by first deploying the CloudnativePG operator, as the operator provides a bundled version of the extension.
This tutorial is intended for cloud platform administrators and architects, ML engineers, and MLOps (DevOps) professionals interested in deploying PostgreSQL database clusters on GKE.
Objectives
In this tutorial, you learn how to:
- Deploy GKE infrastructure for PostgreSQL.
- Install pgvector extension on the PostgreSQL cluster deployed to GKE.
- Deploy and configure the CloudNativePG PostgreSQL operator with Helm.
- Upload a demo dataset and run search queries with Jupyter Notebook.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.
Before you begin
In this tutorial, you use Cloud Shell to run commands. Cloud Shell is a shell environment for managing resources hosted on Google Cloud. It comes preinstalled with the Google Cloud CLI, kubectl, Helm and Terraform command-line tools. If you don't use Cloud Shell, you must install the Google Cloud CLI.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials APIs:
gcloud services enable cloudresourcemanager.googleapis.com
compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com - Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager, Compute Engine, GKE, and IAM Service Account Credentials APIs:
gcloud services enable cloudresourcemanager.googleapis.com
compute.googleapis.com container.googleapis.com iamcredentials.googleapis.com -
Grant roles to your user account. Run the following command once for each of the following IAM roles:
roles/compute.securityAdmin, roles/compute.viewer, roles/container.clusterAdmin, roles/container.admin, roles/iam.serviceAccountAdmin, roles/iam.serviceAccountUser
gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
- Replace
PROJECT_ID
with your project ID. -
Replace
USER_IDENTIFIER
with the identifier for your user account. For example,user:[email protected]
. - Replace
ROLE
with each individual role.
- Replace
Set up your environment
To set up your environment with Cloud Shell, follow these steps:
Set environment variables for your project, region, and a Kubernetes cluster resource prefix:
export PROJECT_ID=PROJECT_ID export KUBERNETES_CLUSTER_PREFIX=postgres export REGION=us-central1
- Replace
PROJECT_ID
with your Google Cloud project ID.
This tutorial uses the
us-central1
region.- Replace
Clone the sample code repository from GitHub:
git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
Navigate to the
postgres-pgvector
directory:cd kubernetes-engine-samples/databases/postgres-pgvector
Create your cluster infrastructure
In this section, you run a Terraform script to create a private, highly-available, regional GKE cluster to deploy your PostgreSQL database.
You can choose to deploy PostgreSQL using a Standard or Autopilot cluster. Each has its own advantages and different pricing models.
Autopilot
To deploy the Autopilot cluster infrastructure, run the following commands in the Cloud Shell:
export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-autopilot init
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-autopilot apply \
-var project_id=${PROJECT_ID} \
-var region=${REGION} \
-var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
GKE replaces the following variables at runtime:
GOOGLE_OAUTH_ACCESS_TOKEN
uses thegcloud auth print-access-token
command to retrieve an access token that authenticates interactions with various Google Cloud APIsPROJECT_ID
,REGION
, andKUBERNETES_CLUSTER_PREFIX
are the environment variables defined in the Set up your environment section and assigned to the new relevant variables for the Autopilot cluster you are creating.
When prompted, type yes
.
Terraform creates the following resources:
- A custom VPC network and private subnet for the Kubernetes nodes.
- A Cloud Router to access the internet through Network Address Translation (NAT).
- A private GKE cluster in the
us-central1
region. - A
ServiceAccount
with logging and monitoring permissions for the cluster. - Google Cloud Managed Service for Prometheus configuration for cluster monitoring and alerting.
The output is similar to the following:
...
Apply complete! Resources: 11 added, 0 changed, 0 destroyed.
...
Standard
To deploy the Standard cluster infrastructure, run the following commands in the Cloud Shell:
export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-standard init
terraform -chdir=../postgresql-cloudnativepg/terraform/gke-standard apply \
-var project_id=${PROJECT_ID} \
-var region=${REGION} \
-var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
GKE replaces the following variables at runtime:
GOOGLE_OAUTH_ACCESS_TOKEN
uses thegcloud auth print-access-token
command to retrieve an access token that authenticates interactions with various Google Cloud APIs.PROJECT_ID
,REGION
, andKUBERNETES_CLUSTER_PREFIX
are the environment variables defined in Set up your environment section and assigned to the new relevant variables for the Standard cluster that you are creating.
When prompted, type yes
. It might take several minutes for these commands to
complete and for the cluster to show a ready status.
Terraform creates the following resources:
- A custom VPC network and private subnet for the Kubernetes nodes.
- A Cloud Router to access the internet through Network Address Translation (NAT).
- A private GKE cluster in the
us-central1
region with autoscaling enabled (one to two nodes per zone). - A
ServiceAccount
with logging and monitoring permissions for the cluster. - Google Cloud Managed Service for Prometheus configuration for cluster monitoring and alerting.
The output is similar to the following:
...
Apply complete! Resources: 14 added, 0 changed, 0 destroyed.
...
Connect to the cluster
Configure kubectl
to fetch credentials and communicate with your new GKE cluster:
gcloud container clusters get-credentials \
${KUBERNETES_CLUSTER_PREFIX}-cluster --region ${REGION} --project ${PROJECT_ID}
Deploy the CloudNativePG operator
Deploy the CloudNativePG to your Kubernetes cluster using a Helm chart:
Check the version of Helm:
helm version
Update the version if it's older than 3.13:
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
Add the CloudNativePG operator Helm Chart repository:
helm repo add cnpg https://cloudnative-pg.github.io/charts
Deploy the CloudNativePG operator using the Helm command-line tool:
helm upgrade --install cnpg \ --namespace cnpg-system \ --create-namespace \ cnpg/cloudnative-pg
The output is similar to the following:
Release "cnpg" does not exist. Installing it now. NAME: cnpg LAST DEPLOYED: Fri Oct 13 13:52:36 2023 NAMESPACE: cnpg-system STATUS: deployed REVISION: 1 TEST SUITE: None ...
Deploy the PostgreSQL vector database
In this section, you deploy the PostgreSQL vector database.
Create a namespace
pg-ns
for the database:kubectl create ns pg-ns
Apply the manifest to deploy PostgreSQL cluster. The cluster manifest enables the pgvector extension.
kubectl apply -n pg-ns -f manifests/01-basic-cluster/postgreSQL_cluster.yaml
The
postgreSQL_cluster.yaml
manifest describes the Deployment:Check the status of the cluster:
kubectl get cluster -n pg-ns --watch
Wait for the output to show a status of
Cluster in healthy state
before you move to the next step.
Upload demo dataset and run search queries with Jupyter Notebook
In this section, you upload vectors into a PostgreSQL table and run semantic search queries using SQL syntax.
In the following example, you use a dataset from a CSV file that contains a list of books in different genres. Pgvector serves as a search engine, and the Pod you create serves as a client querying the PostgreSQL database.
Wait for the PostgreSQL leader Pod to be created and ready:
while [[ $(kubectl get pod -l cnpg.io/cluster=gke-pg-cluster,role=primary -n pg-ns -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}') != "True" ]]; do sleep 5 done
Create the Configmap with the
books-dataset
and run the Jupyter Pod to interact with your PostgreSQL cluster:kubectl create -n pg-ns configmap books-dataset --from-file=manifests/02-notebook/dataset.csv kubectl create -n pg-ns configmap notebook --from-file=manifests/02-notebook/vector-database.ipynb kubectl apply -n pg-ns -f manifests/02-notebook/jupyter.yaml
- The Secret named
gke-pg-cluster-superuser
that is created by the CloudNativePG operator is mounted to the client Pod as environment variables namedCLIENTUSERNAME
andCLIENTPASSWORD.
- The
books-dataset
ConfigMap contains acsv
file with book data for the PostgreSQL database. - The
demo-app
ConfigMap contains Python code to create the PostgreSQL table frombooks-dataset
.
The
jupyter.yaml
manifest describes thenotebook
Deployment and its Service:- The Secret named
Wait for GKE to start the Jupyter Pod:
kubectl wait pods -l app=jupyter-notebook --for condition=Ready --timeout=300s -n pg-ns
Get the URL with the access token to connect to Jupyter:
export EXTERNAL_IP=$(kubectl -n pg-ns get svc notebook --output jsonpath='{.status.loadBalancer.ingress[0].ip}') kubectl logs deploy/notebook -n pg-ns| grep '^ .*http://127'|sed "s|127.0.0.1|${EXTERNAL_IP}|"
The output is similar to the following:
http://34.123.21.1:8888/tree?token=a1d48d3531c48328695d6901004c94060aa0aa3554ff7463
Open this URL and click the
vector-database.ipynb
file.Click Run > Run all cells. Jupyter executes the code and performs a search query for the text
drama about people and unhappy love
.This query performs a semantic search against the
documents
table in PostgreSQL, retrieving a maximum of two results with highest match score relevant to your query.The output is similar to the following:
Title: Romeo and Juliet, Author: William Shakespeare, Paul Werstine (Editor), Barbara A. Mowat (Editor), Paavo Emil Cajander (Translator) In Romeo and Juliet, Shakespeare creates a violent world, in which two young people fall in love. It is not simply that their families disapprove; the Montagues and the Capulets are engaged in a blood feud.In this death-filled setting, the movement from love at first sight to the lovers' final union in death seems almost inevitable. And yet, this play set in an extraordinary world has become the quintessential story of young love. In part because of its exquisite language, it is easy to respond as if it were about all young lovers. --------- Title: A Midsummer Night's Dream, Author: William Shakespeare, Paul Werstine (Editor), Barbara A. Mowat (Editor), Catherine Belsey (Contributor) Shakespeare's intertwined love polygons begin to get complicated from the start--Demetrius and Lysander both want Hermia but she only has eyes for Lysander. Bad news is, Hermia's father wants Demetrius for a son-in-law. On the outside is Helena, whose unreturned love burns hot for Demetrius. Hermia and Lysander plan to flee from the city under cover of darkness but are pursued by an enraged Demetrius (who is himself pursued by an enraptured Helena). In the forest, unbeknownst to the mortals, Oberon and Titania (King and Queen of the faeries) are having a spat over a servant boy. The plot twists up when Oberon's head mischief-maker, Puck, runs loose with a flower which causes people to fall in love with the first thing they see upon waking. Throw in a group of labourers preparing a play for the Duke's wedding (one of whom is given a donkey's head and Titania for a lover by Puck) and the complications become fantastically funny. ---------
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete the project
The easiest way to avoid billing is to delete the project you created for this tutorial.
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
If you deleted the project, your clean up is complete. If you didn't delete the project, proceed to delete the individual resources.
Delete individual resources
Set environment variables.
export PROJECT_ID=${PROJECT_ID} export KUBERNETES_CLUSTER_PREFIX=postgres export REGION=us-central1
Run the
terraform destroy
command:export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token) terraform -chdir=../postgresql-cloudnativepg/terraform/FOLDER destroy \ -var project_id=${PROJECT_ID} \ -var region=${REGION} \ -var cluster_prefix=${KUBERNETES_CLUSTER_PREFIX}
Replace
FOLDER
with eithergke-autopilot
orgke-standard
, depending on the type of GKE cluster you created.When prompted, type
yes
.
What's next
- Explore how to deploy PostgreSQL clusters on GKE using CloudNativePG operator.
- Learn about the best practices for deploying databases on GKE.
- Discover solutions for running data-intensive workloads with GKE.