
3536
Of your peers have already downloaded this article
6:30 Minutes
The most insightful time you'll spend today!
BigQuery Omni: Your Solution for Multi-Cloud Geospatial Analytics

1504
Of your peers have already read this article.
6:30 Minutes
The most insightful time you'll spend today!
As we become increasingly reliant on technology to make decisions, geospatial data is becoming more critical than ever. It is a powerful resource that can be used to solve a variety of problems, from tracking the movement of goods, identifying interest areas and potential areas of disaster.
Geospatial data incorporates data with a geographic component, such as latitude and longitude coordinates, addresses, postal codes, or place names, and can be obtained from a variety of sources, including satellites, sensors, and surveys, making it an incredibly powerful tool with a broad range of applications.
One of the key features of BigQuery, Google Cloud’s serverless enterprise data warehouse, is its ability to analyze geospatial data. However, oftentimes geospatial data sits in a variety of public clouds, not just Google Cloud. To access it effectively, you need a multi-cloud analytics solution that lets you capitalize on the distinct capabilities of each cloud platform, while extracting insights and value from data sitting across multiple cloud platforms.
BigQuery Omni is a multi-cloud analytics solution that enables the analysis of data stored across public cloud environments, including Google Cloud, Amazon Web Services (AWS) and Microsoft Azure, without the need to transfer the data. With BigQuery Omni, users can employ the same SQL queries and tools used to analyze data in Google Cloud to analyze data in other clouds, making it easier to gain insights from all data, regardless of the storage location. For businesses using multiple clouds, BigQuery Omni is an excellent tool to unify analytics and optimize the value of data.

With BigQuery Omni, organizations can analyze location-based information or geographic components, such as latitude and longitude coordinates, addresses, postal codes, or place names without even copying their data to Google Cloud. For example, you could use BigQuery Omni to analyze data from a fleet of delivery vehicles to track their location and identify potential problems.
BigQuery Omni and geospatial data analysis
If you are working with geospatial data, BigQuery Omni is a powerful tool that can help you to get insights from your data. It is scalable, reliable, and secure, making it a great option for unifying your analytics and getting the most out of your data.
Here are a few examples of ways organizations might use BigQuery Omni for geospatial data:
- A transportation company could use BigQuery Omni to analyze data from GPS sensors in its vehicles to track the movement of its fleet and identify potential problems.
- A retail company could use BigQuery Omni to analyze data from its point-of-sale systems to track customer behavior and identify trends.
- A government agency could use BigQuery Omni to analyze data from its weather sensors to track the movement of storms and identify areas at risk of flooding.
BigQuery Omni and geospatial data can be used together to gain insights into a variety of business problems. Specifically, some of the advantages of using BigQuery Omni and geospatial data include:
- Access to quality geospatial data: BigQuery supports loading of newline-delimited GeoJSON files and provides built-in support for loading and querying geospatial data. Data from public data sources like BigQuery public datasets, the Earth Engine catalog, and the United States Geological Survey (USGS) can be easily integrated into your BigQuery environment. Earth Engine has an integrated data catalog with a comprehensive collection of analysis-ready datasets, including satellite imagery and climate data. This data can be combined with proprietary data sources such as SAP, Oracle, Esri ArcGIS Server, Carto, and QGIS.
- Loading and preprocessing of geospatial data: BigQuery has built-in support for loading and querying geospatial data types, and you can use partner solutions such as FME Spatial ETL to load data.
- Working with different geospatial data types and formats: BigQuery supports a variety of file types and formats including WKT, WKB, CSV and GeoJSON.
- Coordinate reference systems: BigQuery’s geography data type is globally consistent. That means that your data is registered to the WGS84 reference system and your analyses can span a city block or multiple continents.
Overall, geospatial analytics with BigQuery Omni provides a wide range of technical capabilities for processing and analyzing geospatial data, making it a powerful tool for businesses that need to work with location-based data.
Analyzing geospatial data with BigQuery Omni
Imagine a retailer who has a large chain of department stores with locations all over the country. They are looking to expand their business and want to identify areas with high sales potential. They want a way to get a better understanding of their sales volume within specific geographic boundaries. To achieve this goal, the retailer turns to the GIS (Geographic Information System) functions built into BigQuery. Here are the steps what the retailer takes to analyze this dataset:
Step 1 : An initial orders dataset on AWS S3 contains 5.54 million rows, and with separate locations (300 rows) and zipcode (33144 rows) metadata files on AWS S3.
Orders Parquet files:

Location and Zipcode files:

Step 2 : The retailer uses BigQuery Omni to establish a connection between the data stored in AWS and BigQuery, enabling them to access the S3 datasets externally.
External Connection for AWS

External Table for orders

External Table for locations

External Table for zipcode

Step 3 : They combine the orders and locations datasets using BigQuery Omni, and remotely aggregate the data on AWS. Joining this dataset with geospatial datasets helps them derive geospatial coordinates.
The final aggregated dataset is reduced to 23 rows. Subsequently, they bring back the result dataset, which contains just 23 rows. This helps them reduce the extraction of millions of rows to just 23 rows for their geospatial analytics.
Select sales.store_city store_city,
sales.number_of_sales_last_10_mins number_of_sales_last_10_mins,
sales.store_zip store_zip,
ST_GeogPoint(zip_lat_lng.longitude ,
zip_lat_lng.latitude ) geo
FROM (
SELECT
FORMAT_DATETIME("%X",
CURRENT_DATETIME("America/Los_Angeles")) current_time,
MAX(DATETIME(time_of_sale,
"America/Los_Angeles")) time_of_last_sale,
COUNT(1) number_of_sales_last_10_mins,
locations.city store_city,
locations.zip store_zip
FROM
`bqomni-blog.aws_locations.orders_small` sales
JOIN
`bqomni-blog.aws_locations.locations` locations
ON
sales.store_id = locations.id
GROUP BY
locations.city,
locations.zip ) sales
JOIN
`bqomni-blog.aws_locations.zipcode` zip_lat_lng
ON
cast(sales.store_zip as INT) = cast(zip_lat_lng.zipcode as INT)
WHERE ST_WITHIN( ST_GeogPoint(zip_lat_lng.longitude , zip_lat_lng.latitude ) ,ST_GeogFromText(zip_lat_lng.zipcode_geom ) )
AND zip_lat_lng.state_name = "New York"
ORDER BY number_of_sales_last_10_minsAggregated Sales data by region

To build richer views of their sales volume data, the retailer uses BigQuery GeoViz integration, a powerful tool that allows for visualizing geographic data on maps.BigQuery Geo Viz is a web tool for visualization of geospatial data in BigQuery using Google Maps APIs. You can run a SQL query and display the results on an interactive map

BigQuery Geo view for sales data analysis
With the geo-tagged data in place, the retailer can now see regional sales volume, sales density, distribution by department by time, and distribution within department, all powered through BigQuery.

Satellite view

Benefits of using BigQuery Omni
Beyond geospatial analysis, BigQuery Omni offers a number of benefits, including:
Reduced costs: BigQuery Omni’s ability to eliminate data transfers between clouds can help organizations reduce costs and simplify data management, making it a valuable tool for multi-cloud analytics. Also, the ability to access and analyze data across multiple clouds can reduce the need for data replication and synchronization, which can further simplify the ETL process and improve data consistency.
Unified governance: BigQuery Omni uses the same security controls as BigQuery, which include features such as encryption, access controls, and audit logs, to help protect data from unauthorized access.
Single pane for analytics: BigQuery Omni provides a single interface for querying data across all three clouds, which can simplify the process of analyzing data and reduce the need for organizations to use multiple analytics tools.
Flexibility: Analyze data stored in any of the supported cloud storage services, giving organizations the flexibility to work with the data they have regardless of where it’s located.
BigQuery Omni is a valuable tool for geospatial analysis because it allows you to analyze data from multiple sources without having to move the data. This can save you time and money, and it can also help you to get more accurate insights from your data.If you are looking for a way to improve the accuracy, efficiency, and decision-making of your business, using BigQuery Omni to analyze geospatial data can be a powerful tool.
References
- Omni-introduction
- Omni-benefits
- Omni-aws-create-connection
- Omni-azure-create-connection
- BigQuery Omni Retail Demo on Looker
- Omni-pricing
- Working with Geospatial Data
- Geospatial Analytics – Intro
Learn more about how BigQuery Omni can help your organization.
How to Build A Basic Image Search Utility for Natural Language Queries

4705
Of your peers have already read this article.
6:00 Minutes
The most insightful time you'll spend today!
This post shows how to build an image search utility using natural language queries. Our aim is to use different GCP services to demonstrate this. At the core of our project is OpenAI’s CLIP model. It makes use of two encoders – one for images and one for texts. Each encoder is trained to learn representations such that similar images and text embeddings are projected as close as possible.
We will first create a Flask-based REST API capable of handling natural language queries and matching them against relevant images. We will then demonstrate the use of the API through a Flutter-based web and mobile application. Figure 1 shows how our final application would look like:

All the code shown in this post is available as a GitHub repository. Let’s dive in.
Application at a high-level
Our application will take two queries from the user:
- Tag or keyword query. This is needed in order to pull a set of images of interest from Pixabay. You can use any other image repositories for this purpose. But we found Pixabay’s API to be easier to work with. We will cache these images to optimize the user experience. Suppose we wanted to find images that are similar to this query: “horses amidst flowers”. For this, we’d first pull in a few “horse” images and then run another utility to find out the images that best match our query.
- Longer or semantic query that we will use to retrieve the images from the pool created in the step above. These images should be semantically similar to this query.
Note: Instead of two queries, we could have only taken a single long query and run named-entity extraction to determine the most likely important keywords to run the initial search with. For this post, we won’t be using this approach.
Figure 2 below depicts the architecture design of our application and the technical stack used for each of the components.

Figure 2 also presents the core logic of the API we will develop in bits and pieces in this post. We will deploy this API on a Kubernetes cluster using the Google Kubernetes Engine (GKE). The following presents a brief directory structure of our application code-base:

Next, we will walk through the code and other related components for building our image search API. For various machine learning-related utilities, we will be using PyTorch.
Building the backend API with Flask
First, we’d need to fetch a set of images with respect to user-provided tags/keywords before performing the natural language image search. The utility below from the pixabay_utils.py script can do this for us:
def fetch_images_tag(pixabay_search_keyword, num_images):"""Fetches images from Pixabay w.r.t a keyword.:param pixabay_search_keyword: Keyword to perform the search on Pixabay.:param num_images: Number of images to retrieve.:return: List of PIL images.:return: List of image URLs."""query = (PIXABAY_API+ "&q="+ pixabay_search_keyword.lower()+ "&image_type=photo&safesearch=true&per_page="+ str(num_images))response = requests.get(query)output = response.json()all_images = []all_image_urls = []for each in output["hits"]:imageurl = each["webformatURL"]response = requests.get(imageurl)image = Image.open(BytesIO(response.content)).convert("RGB")all_images.append(image)all_image_urls.append(imageurl)return (all_images, all_image_urls)
Note that all the API utilities are logging relevant information. But for brevity, we have omitted the lines of code responsible for that. Next, we will see how to invoke the CLIP model and select the images that would best match a given query semantically. For this, we’ll be using Hugging Face, an easy-to-use Python library offering state-of-the-art NLP capabilities. We’ll collate all the logic related to this search inside a SimilarityUtil class:
class SimilarityUtil:def __init__(self):self.model = CLIPModel.from_pretrained(CLIP_MODEL)self.processor = CLIPProcessor.from_pretrained(CLIP_PREPROCESSOR)self.device = "cuda" if torch.cuda.is_available() else "cpu"def perform_sim_search(self, images, query_phrase, top_k=3):"""Performs similarity search between the images and query.:param images: A list of PIL images initially retrieved withrespect to some entity e.g. Tiger.:param query_phrase: A list containing a single text query,e.g. "Tiger drinking water".:param top_k: Number of top images to return from `images`.:return: Top-k indices matching the query semantically andtheir similarity scores."""model = self.model.to(self.device)# Obtain the text-image similarity scoreswith torch.no_grad():inputs = self.processor(text=[query_phrase], images=images, return_tensors="pt", padding=True)inputs = inputs.to(self.device)outputs = model(**inputs)# Image-text similarity scoreslogits_per_image = outputs.logits_per_image.cpu()(top_indices, top_scores) = self.sort_scores(logits_per_image, top_k)return (top_indices, top_scores)def sort_scores(self, scores, top_k):"""Sorts the scores in a descending manner.:param scores: Scores to sort through.:param top_k: Number of top scores to return.:return: Top-k scores and their indices."""values, indices = scores.squeeze().topk(top_k)top_indices, top_scores = [], []for score, index in zip(values, indices):top_indices.append(int(index.numpy()))score = score.numpy().tolist()top_scores.append(round(score, 3))return (top_indices, top_scores)
CLIP_MODEL uses a ViT-base model to encode the images for generating meaningful embeddings with respect to the provided query. The text-based query is also encoded using A Transformers-based model for generating the embeddings. These two embeddings are matched with one another during inference. To know more about the particular methods we are using for the CLIP model please refer to this documentation from Hugging Face.
In the code above, we are first invoking the CLIP model with images and the natural language query. This gives us a vector (logits_per_image) that contains the similarity scores between each of the images and the query. We then sort the vector in a descending manner. Note that we are initializing the CLIP model while instantiating the SimilarityUtil to save us the model loading time. This is the meat of our application and we have tackled it already. If you want to interact with this utility in a live manner you can check out this Colab Notebook.
Now, we need to collate our utilities for fetching images from Pixabay and for performing the natural language image search inside a single script – perform_search.py. Following is the main class of that script:
class Searcher:def __init__(self):self.similarity_model = SimilarityUtil()def get_similar_images(self, keyword, semantic_query, pixabay_max, top_k):"""Finds semantically similar images.:param keyword: Keyword to search with on Pixabay.:param semantic_query: Query to find semantically similar images retrieved from Pixabay.:param pixabay_max: Number of maximum images to retrieve from Pixabay.:param top_k: Top-k images to return.:return: Tuple of top_k URLs and the similarity scores of the images present inside the URLs."""images_redis_key = keyword + "_images"urls_redis_key = keyword + "_urls"if redis_client.exists(images_redis_key) and redis_client.exists(urls_redis_key):keyword_images = redis_client.get(images_redis_key)keyword_image_urls = redis_client.get(urls_redis_key)else:(keyword_images, keyword_image_urls) = fetch_images_tag(keyword, pixabay_max)redis_client.set(images_redis_key, keyword_images)redis_client.set(urls_redis_key, keyword_image_urls)(top_indices, top_scores) = self.similarity_model.perform_sim_search(keyword_images, semantic_query, top_k)top_urls = [keyword_image_urls[index] for index in top_indices]return (top_urls, top_scores)
Here, we are just calling the utilities we had previously developed to return the URLs of the most similar images and their scores. What is even more important here is the caching capability. For that, we combined GCP’s MemoryStore and a Python library called direct-redis. More on setting up MemoryStore later.
MemoryStore provides a fully managed and low-cost platform for hosting Redis instances. Redis databases are in memory and light-weight making them an ideal candidate for caching. In the code above, we are caching the images fetched from Pixabay and their URLs. So, in the event of a cache hit, we won’t need to call the CLIP model and this will tremendously improve the response time of our API.
Other options for caching
We can cache other elements of our application. For example, the natural language query. When searching through the cached entries to determine if it’s a cache hit, we can compare two queries for semantic similarity and return results accordingly.
Consider that a user had entered the following natural language query: “mountains with dark skies”. After performing the search, we’d cache the embeddings of this query. Now, consider that another user entered another query: “mountains with gloomy ambiance”. We’d compute its embeddings and run a similarity search with the cached embeddings. We’d then compare the similarity scores with respect to a threshold and parse the most similar queries and their corresponding results. In case of a cache miss, we’d just call the image search utilities we developed above.
When working on real-time applications we often need to consider these different aspects and decide what enhances the user experience and maximizes business at the same time.
All that’s left now for the backend is our Flask application – main.py:
@app.route("/search", methods=["GET"])def get_images():tag = request.args.get("t").lower()query = request.args.get("s_query").lower()top_k = request.args.get("k")(top_urls, top_scores) = searcher.get_similar_images(tag, query, MAX_PIXABAY_SEARCH, int(top_k))return jsonify({"top_urls": top_urls, "top_scores": top_scores})
Here we are first parsing the query parameters from the request payload of our search API. We are then just calling the appropriate function from perform_search.py to handle the request. This Flask application is also capable of handling CORS. We do this via the flask_cors library:
cors = CORS(app,resources={r"/search/*": {"origin": "*"},r"/test/*": {"origin": "*"},},)
And this is it! Our API is now ready for deployment.
Deployment with Compute Engine and GKE
The reason why we wanted to deploy our API on Kubernetes is because of the flexibility Kubernetes offers for managing deployments. When operating at scale, auto scalability and load balancing are very important. With the comes the requirement of security — we’d not want to expose the utilities for interacting with any internal services such as databases. With Kubernetes, we can achieve all these easily and efficiently.
GKE provides secured and fully managed functionalities for operationalizing Kubernetes clusters. Here are the steps to deploy the API on GKE at a glance:
- We first build a Docker image for our API and then push it to the Google Container Registry (GCR).
- We then create a Kubernetes cluster on GKE and initialize a deployment.
- We then add scalability options.
- If any public exposure is needed for the API, we then tackle it.
We can assimilate all the above into a shell script – k8s_deploy.sh:
## Docker build and push ### We are inside the `server` directorydocker build -t gcr.io/${PROJECT_ID}/search_service .docker push gcr.io/${PROJECT_ID}/search_service## Deploy on a GKE cluster ### Configure the Docker command-line tool to authenticate to Container Registrygcloud auth configure-docker# Create a Kubernetes clustergcloud container clusters create image-search-nlp# Create a deploymentkubectl create deployment clip-search --image=gcr.io/${PROJECT_ID}/search_service# Number of worker replicaskubectl scale deployment clip-search --replicas=3# HorizontalPodAutoscaler resourcekubectl autoscale deployment clip-search --cpu-percent=80 --min=1 --max=5# Expose deploymentkubectl expose deployment clip-search --name=clip-search-service --type=LoadBalancer --port 80 --target-port 8080
These steps are well explained in this tutorial that you might want to refer to for more details. We can configure all the dependencies on our local machine and execute the shell script above. We can also use the GCP Console to execute it since a terminal on the GCP Console is pre-configured with the system-level dependencies we’d need. In reality, the Kubernetes cluster should only be created once and different deployment versions should be created under it.
After the above shell script is run successfully, we can run kubectl get service to know the external IP address of the service we just deployed:
NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGEclip-search-service 10.3.251.122 203.0.113.0 80:30877/TCP 10s
We can now consume this API with the following base URI: http://203.0.113.0/. If we wanted to deal with only http-based API requests, then we are done here. But secured communication is often a requirement in order for applications to operate reliably. In the following section, we are to discuss how to configure the additional items to allow our Kubernetes cluster to allow https requests.
Configurations for handling https requests with GKE
A secure connection is almost often a must-have requirement in modern client/server applications. The front-end Flutter application would be hosted on GitHub Pages for this project, and it requires https-based connection as well. Even if configuring https connection particularly for a GKE-based cluster can be considered a chore, its setup might seem daunting at first.
There are six steps to configure https connection in the GKE environment:
- You need to have a domain name, and there are a lot of inexpensive options that you can buy. For instance, mlgde.com domain for this project is acquired via Gabia which is a Korean service provider.
- A reserved (static) external IP address has to be acquired via gcloud command or GCP console.
- You need to bind the domain name with the acquired external IP address. This is a platform-specific configuration that issued the domain name to you.
- There is a special ManagedCertificate resource which is specific to the GKE environment. ManagedCertificate resource specifies the domain that the SSL certificate will be created for, so you need this.
- An Ingress resource should be created by listing the static external IP address, ManagedCertificate resource, and the service name and port which the incoming traffic will be routed to. The Service resource could remain the same as in the above section with only changes from LoadBalancer to ClusterIP.
- Last but not least, you need to modify the existing Flask application and Deployment resource to support liveness and readiness probes which are used to check the health status of the Deployment. The Flask application side can be simply modified with the flask-healthz Python package, and you only need to add
livenessProbeandreadinessProbesections in the Deployment resource. In the code example below, thelivenessProbeandreadinessProbeare checked via/aliveand/readyendpoints respectively.
from flask_healthz import healthzfrom flask_healthz import HealthErrorapp = Flask(__name__)app.register_blueprint(healthz, url_prefix="/")def printok():print("Everything is fine")def liveness():try:printok()except Exception:raise HealthError("Can't connect to the file")def readiness():try:printok()except Exception:raise HealthError("Can't connect to the file")app.config.update(HEALTHZ = {"alive": "main.liveness","ready": "main.readiness",})
One thing to be careful of is the initialDelaySeconds attribute of the probes. It is uncommon to configure this attribute with a big number, but it could be bigger than 90 – 120 seconds depending on the size of the model to be used. For this project, it is configured in 90 seconds in order to wait until the CLIP model is fully loaded into memory (full YAML script here).
livenessProbe:httpGet:path: /aliveport: 8080initialDelaySeconds: 90periodSeconds: 10readinessProbe:httpGet:path: /readyport: 8080initialDelaySeconds: 90periodSeconds: 10
Again, these steps may seem daunting at first, but it will become clear when you have done it once. Here is the official document for Using Google-managed SSL certificates You can find all the GKE-related resources used in this project here.
Once every step is completed you should be able to see your server application running on the GKE environment. Please make sure to run kubectl apply command whenever you create Kubernetes resources such as Deployment, Service, Ingress, and ManagedCertificate, and it is important to wait for more than 10 minutes until the ManagedCertifcate provisioning is done.
You can run gcloud compute addresses list command to find out the static external IP address that you have configured.
NAME ADDRESS/RANGE TYPE PURPOSE NETWORK REGION SUBNET STATUSgde 34.149.231.34 EXTERNAL IN_USE
Then, the IP address has to be mapped to the domain. Figure 3 is a screenshot of a dashboard from where we got the mlgde.com domain. It clearly shows mlgde.com is mapped to the static external IP address configured in GCP.

In case you’re wondering why we didn’t deploy this application on App Engine, well that is because of the compute needed to execute the CLIP model. App Engine instance won’t fit in that regime. We could have also incorporated compute-heavy capabilities via a VPC Connector. That is a design choice that you and your team would need to consider. In our experiments, we found the GKE deployment to be easier and suitable for our needs.
Infrastructure for the CLIP model
As mentioned earlier, at the core of our application is the CLIP model. It is computationally a bit more expensive than the regular deep learning models. This is why it makes sense to have the hardware infrastructure set up accordingly to execute it. We ran a small benchmark in order to see how a GPU-based environment could be beneficial here.
We ran the CLIP on a Tesla P100-based machine and also on a standard CPU-only machine 1000 times. The code snippet below is the meat of what we executed:
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"start_time = time.time()for _ in range(1000):with torch.no_grad():model = model.to(DEVICE)inputs = processor(text=[semantic_search_phrase],images=all_images, return_tensors="pt", padding=True)inputs = inputs.to(DEVICE)outputs = model(**inputs)end_time = time.time() - start_timeprint(f"Total time: {end_time:.3f} seconds.")
As somewhat expected, with the GPU, the code took 13 minutes to complete execution. With no GPU, it took about 157 minutes.
It is uncommon to leverage GPUs for model prediction because of cost restrictions, but sometimes we have to access GPUs for deploying a big model like CLIP. We configured a GPU-based cluster on GKE and compared the performance differences with and without it. It took about 1 second to handle a request with GPU and MemoryStore cache while it took more than 4 seconds with MemoryStore only (without the GPUs).
For the purposes of this post, we used a CPU-based cluster on Kubernetes. But It is easy to configure GPU usage in a GKE cluster. This document shows you how to do so. For a short summary, there are two steps. First, a node should be configured with GPUs when creating a GKE cluster. Second, GPU drivers should be installed in GKE nodes. You don’t need to visit and manually install GPU drivers for each node by yourself. Rather you can simply apply the DaemonSet resource to GKE as described here.
Setting up MemoryStore
In this project, we first query the general concept of images to Pixabay, then we filter the images with a semantic query using CLIP. It means we can cache the initially retrieved images from Pixabay for the next specific semantic query. For instance, you may want to search with “gentleman wearing tie” at first, then you may want to retry searching for “gentleman wearing glass”. In this case, the base images remain all the same, so they could be stored in a cache server like Redis.
MemoryStore is a GCP service wrapping the Redis which is an in-memory data store, so you can simply use a standard Redis Python package for accessing it. The only thing to be careful about when provisioning a MemoryStore Redis instance is to make sure it is in the same region where your GKE cluster or Compute Engine instance is.

The code snippet below shows how to make a connection to the Redis instance in Python. Nothing specific to GCP, but you only need to be aware of the usage of the standard redis-py package.
# REDISHOST is the IP address to the MemoryStore instanceredis_host = os.environ.get("REDISHOST", "localhost")redis_port = int(os.environ.get("REDISPORT", 6379))redis_client = redis.StrictRedis(host=redis_host, port=redis_port)
After creating a connection, you can store and retrieve data from MemoryStore. There are more advanced use cases of Redis, but we only used exists, get, and set methods for the demonstration purpose. These methods should be very familiar if you know maps, dictionaries, or other similar data structures. For the code portion that uses Redis-related utilities, please refer to the Searcher Python class we discussed in an earlier section.
In the URLs below, you can find side-by-side comparisons of using MemoryStore:
- Without MemoryStore: https://youtu.be/7B88Eyrd-4s
- With MemoryStore (1st try): https://youtu.be/LE6xeEIRuMM
- With MemoryStore (2nd try): https://youtu.be/rRfK17sdk84
Putting everything together
All that’s left now is to collate the different components we developed in the sections above and deploy our application with a frontend. All the frontend-related code is present here.
- The front-end application is written in the Flutter development kit. The main screen contains two text fields for queries to Pixabay and CLIP model respectively. When you click the “Send Query” button, it will send out a RestAPI request to the server. After receiving the result back from the server, the retrieved images from the semantic query will be displayed at the bottom section of the screen.
- Please note that a Flutter application can be deployed to various environments including desktop, web, iOS, and Android. In order to keep as simple as possible, we chose to deploy the application to the GitHub Pages. Whenever there is any change to a client-side source directory, the GitHub Action will be triggered to build a web page and deploy the latest version to the GitHub Pages.
Our final application is deployed here and it looks like so:

Note that due to constraints, the above-mentioned URL will only be live for one or two months.
It is also possible to redeploy the back-end application with a GitHub Action.
- The very first step is to craft a Dockerfile like below. Since Python is a scripting language, and there are lots of heavy packages that the application is dependent on, it is important to cache the steps. For instance, installing the dependencies should be separated from other commands.
FROM pytorch/pytorch:latestWORKDIR /app# install the dependenciesCOPY requirements.txt requirements.txtRUN pip install -r requirements.txtCOPY . .# set up environment variablesENV PIXABAY_API_KEY="..."ENV REDIS_IN_USE="true"ENV REDISHOST="..."# expose port that Flask app is listening onEXPOSE 8080# run the Flask appCMD [ "python3", "main.py" ]
- With the Dockerfile defined, we can use a GitHub Action like this for automatic deployment.
Edge cases
Since the CLIP model is pre-trained on a large corpus of image and text pairs it’s likely that it may not generalize well to every natural language query we throw at it. Also, because we are limiting the number of images on which the CLIP model can operate, this somehow restricts the expressivity of the model.
We may be able to improve the performance for the second situation by increasing the number of images to be pre-fetched and by indexing them into a low-cost and high-performance database like Datastore.
Costs
In this section, we wanted to provide the readers a breakdown of the costs they might incur in order to consume the various services used throughout the application.
- Frontend hosting
- The front-end application is hosted on GitHub Pages, so there is no expenditure for this.
- Compute Engine
- With an e2-standard-2 instance type without GPUs, the cost is around $48.92 per month. In case you want to add a GPU (NVIDIA K80), the cost goes up to $229.95 per month.
- MemoryStore
- The cost for MemoryStore depends on the size. With 1GB of space, the cost is around $35.77 per month, and whenever you add more GBs the cost will be doubled.
- Google Kubernetes Engine
- The monthly cost for a 3 node GKE cluster with n2-standard-2 (vCPUs: 2, RAM: 8GB without GPUs) is about $170.19. If you add one GPU (NVIDIA K80) to the cluster, the cost goes up to $835.48.
While you may think that is a lot cost-wise, it is good to know that Google gives away free $300 credits when you create a new GCP account. It is still not enough for leveraging GPUs, but it is enough to learn and experiment with GKE and MemoryStore usage.
Conclusion
In this post, we walked through the components needed to build a basic image search utility for natural language queries. We discussed how these different components are connected to each other. Our image search API is able to utilize caching and was deployed on a Kubernetes cluster using GKE. These elements are essential when building a similar service to cater to a much bigger workload. We hope this post will serve as a good starting point for that purpose. Below are some references on similar areas of work that you can explore:
- Building a real-time embeddings similarity matching system
- Detecting image similarity using Spark, LSH and TensorFlow
Acknowledgments: We are grateful to the Google Developers Experts program for supporting us with GCP credits. Thanks to Karl Weinmeister and Soonson Kwon of Google for reviewing the initial draft of this post.
Release of Go 1.18 is A New Milestone for Development of Secure Apps

3210
Of your peers have already read this article.
1:30 Minutes
The most insightful time you'll spend today!
On March 15th, the Go team announced Go 1.18 GA, the latest release of the Go programming language. The culmination of over a decade of design delivers the features our developers demanded: generics, fuzzing, and module workspaces. With this release, Go becomes the first major language to integrate fuzz testing into its core toolchain without using third-party support, further establishing Go as a preferred language for developing secure applications.
Go was created at Google in 2007, designed to help developers build fast, reliable, and secure software. Unlike traditional languages, Go was built for the modern multi-core computing world. Go has emerged as a modern language for developing cloud applications, services, and infrastructure. Today Go powers several of Google’s largest products, and is used by many customers to scale their businesses. Organizations big and small love Go and the community of Go developers, known as “gophers” has grown into a global network with over 2 million users worldwide.
Using the power of Go in the Cloud
When looking at the public repos, over 75% of CNCF projects including Kubernetes are written in Go and 10% of developers are writing in Go worldwide (as of May 2021). Google delivers high performance infrastructure to run key, cloud native, Open Source projects. Our modern cloud infrastructure is based on Kubernetes at its core and our strong support for Istio and Knative have formed the base of some of our leading services like Google Kubernetes Engine (GKE), our managed application platform with Anthos, Cloud Functions, and Cloud Run. Google uses Go extensively for a wide range of applications from our indexing platform that powers Google Search, to the server side optimizations that power Chrome’s 1B+ users, to the infrastructure on which Google cloud is built.
Release Highlights
With this new release of Go 1.18, Generics are the biggest change to Go since the language was created. Go developers told us that they feel that Go lacks critical features, with generics being the main missing piece. With Go 1.18, new and existing Go developers can take advantage of the productivity, performance, and maintenance benefits that generics can bring. We’ve already begun to see the new kinds of libraries and projects gophers are building with generics in its short beta period, and expect this creativity to grow as time goes on.
This Go release also brings native support for fuzzing. Fuzzing is a type of vulnerability testing that throws arbitrary data at a piece of software to expose unknown errors and is emerging as a common testing scheme in enterprise development. Go is now the first major language to provide fuzzing support with no third-party integrations necessary, allowing developers to start building secure software with minimal additional cost. Go’s innovative approach to fuzzing can provide not only security for the current code but also ongoing protection as code and dependencies evolve. With attacks on software becoming more common and complex, vulnerability detection can be a critical part of the enterprise development lifecycle, and Go’s fuzzing capabilities catch vulnerabilities earlier in the lifecycle.
Build securely using Go
At Google we are helping to make Open Source software secure. Open source software is a connective tissue for much of the online world. At Google, we’ve been working to raise awareness of the state of open source security and are committed to helping secure the software supply chain for organizations. Go has been designed to create secure applications, helping to minimize risk as much as possible. Go applications compile down to a single binary without local dependencies. It’s not uncommon to see an application built using only the standard library, or only a couple well-vetted Go dependencies. Go’s dependency management uses tamper-evident transparency log, with built in tooling that helps ensure your dependencies are what you can expect. Go has native encryption, which is used across much of the internet, including key components of Google. Go even supports distroless containers, where there are zero local dependencies to worry about. Google Cloud products like Cloud Build, for CI/CDand Artifact Registry, for container management, and have direct access to Go’s vulnerability database and can provide you instant warnings about security threats.
“At Google we are committed to helping to secure the online infrastructure and applications upon which the world depends. A critical aspect of this mission is being able to understand and verify the security of open source dependency chains. The 1.18 release of Go is an important step towards helping to ensure that developers are able to build secure applications, understand risk when vulnerabilities are discovered, and reduce the impact of cybersecurity attacks” said Eric Brewer, VP Infrastructure, Google Fellow
This launch is a significant milestone for Go that helps developers from around the world build more performant and secure applications that run on any infrastructure. For more information on this release and how to get started with Go, please visit.
Swiggy: Delivering Local Food Within 40 Minutes

8824
Of your peers have already read this article.
1:30 Minutes
The most insightful time you'll spend today!
Founded in 2014, Swiggy started small, delivering food to a few neighborhoods in Bengaluru, India. As the company grew, the team wanted a mapping technology that could help expand the service throughout India.
Swiggy needed a scalable mapping platform that covered a wide geographic area and offered tools to help the company to build an efficient mobile app and website for customers and delivery staff.
Customers find restaurants and order from them using the Android app, iOS app, or the website. Swiggy worked with Google Maps Partner Media Agility and used a variety of Google Maps Platform APIs to develop web and mobile apps that incorporate relevant local restaurant details.
Google Maps Platform Results
- Built a hyper-local delivery service that is growing throughout India at a rate of 25 percent per month
- Deliveries are made quickly, resulting in higher customer satisfaction and retention—users have been so satisfied that nearly 80 percent of its orders are from repeat customers
- Drivers seamlessly handle tens of thousands of orders per day
In order to guarantee fast food delivery, Swiggy returns only restaurants within four to five kilometers of the customer’s location. The Directions API is used by drivers to easily route to restaurants and customers. The customer can track the progress of the delivery and estimated arrival time using a mobile app or the website.
“Google Maps provides the most accurate and reliable data, which is crucial for us because maps and location are central to our business. We also knew Google’s intuitive interface would provide a great customer experience with little to no learning curve… Google Maps’ ability to provide customer location and the distances of nearby restaurants is the backbone of our success, because it ensures a reliable, consistent customer experience,” said Aman Jain, Senior Product Manager, Swiggy.
New to Cloud Functions? Here’s What You Need to Learn

3281
Of your peers have already read this article.
1:00 Minutes
The most insightful time you'll spend today!
Cloud Functions is a fully managed event-driven serverless function-as-a-service (FaaS). It is a small piece of code that runs in response to an event. Because it is fully managed, developers can just write the code and deploy it without worrying about managing the servers or scaling up/down with traffic spikes. It is also fully integrated with Cloud Operations for observability and diagnosis. Cloud Functions is based on an open source FaaS framework which makes it easy to migrate and debug locally.

To use Cloud Functions, just write the logic in any of the supported languages (Go, Python, Java, Node.js, PHP, Ruby, .NET), deploy it using the console, API or Cloud SDK and then trigger it via HTTP(s) request from any service, for example: file uploads to Cloud Storage, events in Pub/Sub or Firebase, or even direct call via Command Line Interface CLI.
There is a generous free tier and the pricing is based on number of events, compute time, memory and ingress/egress requests and costs nothing if the function is idle. For security, using Identity and Access Management IAM you can define which services or personnel can access the function and using the VPC controls you can define network based access.
Cloud Functions use cases
Some Cloud Functions use cases include:
- Integration with third-party services and APIs
- Asynchronous workloads like lightweight ETL
- Lightweight APIs and webhooks
- IoT processing and update of the sensors/devices in the field
- Real-time file processing for use cases such as media transcoding or resizing as soon as the file is uploaded in Google Cloud Storage.
- Real-time ML solutions for use cases such as media translation or image recognition for files uploaded in GCS.
- Backend for chat applications and mobile apps.
Firebase Functions and Cloud Functions, are they different?
If you are a Firebase developer, you’d probably use Firebase Functions. Those are created from the Firebase dashboard / website. Both Cloud Functions and Firebase Functions can do the same things, they just have slightly different signatures and slightly different ways of deploying. Firebase Functions have a local emulator, which Cloud Functions uses the Functions Framework.
For a more in-depth look into Cloud Functions check out the documentation. Once you’ve got your Function up and running, check out some tips and tricks.https://www.youtube.com/embed/LTMChfWBHb0?enablejsapi=1&
For more #GCPSketchnote, follow the GitHub repo. For similar cloud content follow me on Twitter @pvergadia and keep an eye out on thecloudgirl.dev
More Relevant Stories for Your Company

Latest News: Secure Digital Infrastructure Services with Apigee Advanced API Security for Google Cloud
Organizations in every region and industry are developing APIs to enable easier and more standardized delivery of services and data for digital experiences. This increasing shift to digital experiences has grown API usage and traffic volumes. However, as malicious API attacks also have grown, API security has become an important

Google Cloud is a Leader in Q1 2022’s Public Cloud Container Platform: Forrester
We’re thrilled to share the news that leading global research and advisory firm Forrester Research has named Google Cloud a Leader in the recently published report The Forrester WaveTM: Public Cloud Container Platforms, Q1 2022. Forrester evaluated the container and cloud-native offerings of a select group of top public cloud container

Arab Bank Accelerates its App Development and Testing Using Apigee and Anthos
Founded in 1930 and headquartered in Jordan, Arab Bank is one of the oldest banks in the Middle East. Operating out of 28 countries, we’ve earned our customers’ trust with a prudent approach to operations and respect for the cultures and customs in the region. With a few exceptions where cloud providers

How Ather Energy is leveraging the Cloud to build and scale smart mobility solutions for India
In 2013, long before the world was discussing clean energy and sustainable practices, two IIT Madras graduates — Swapnil Jain and Tarun Mehta — had an idea to develop India’s first-ever electrical scooter. This was at a time when auto manufacturers were still focusing on fossil-fuel-driven vehicles and ‘eco-friendly’ mobility






