Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-solution-hybrid-search-alloydb@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cloud-solution-hybrid-search-alloydb v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cloud-solution-hybrid-search-alloydb Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cloud-solution-hybrid-search-alloydb/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-solution-hybrid-search-alloydb for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 15.7 KB
---
name: google-cloud-solution-hybrid-search-alloydb
metadata:
version: "1.0.2"
category: MultiProductSolutions
description: >-
Discovers requirements and generates architectural, design, and deployment
guidance for dynamic hybrid search systems by combining semantic search and
keyword search. Optimized for AlloyDB hybrid search use cases in Google Cloud.
Use when users need vector search combined with structured SQL
filtering, faceted attributes, semantic reranking, in-database AI validation,
or serverless hosting across transactional relational databases, analytical
data warehouses, or managed database engines. DON'T use this skill for simple
keyword-only search, or when a standalone non-relational vector database is
required.
---
# Dynamic Hybrid Search using AlloyDB
This skill provides a workflow to design and implement secure, low-latency, and
high-accuracy hybrid search solutions combining structured dataset filtering,
vector search indexing, faceted metadata filtering, semantic reranking, recall
evaluation, in-database AI validation, database abstraction layers, and
serverless application hosting.
## Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Overview of the workflow
The workflow consists of the following phases:
1. **Requirements discovery**. Gather detailed requirements related to
the cloud workload or use case that the user needs assistance for.
2. **Solution architecture**. Use the requirements that were gathered
in Phase 1 to generate a detailed solution architecture for the cloud
workload or use case.
3. **Solution validation**. Create a plan to validate the generated
solution, generate validation instructions and scripts, and run the
validation.
4. **Solution packaging and presentation**. Consolidate the generated
content and present the solution.
**Important notes about the workflow**:
- **Strict phase separation**: During Phase 1 (Requirements discovery), when you
ask the user clarifying questions, DON'T recommend, propose, or outline any
architectural designs, cloud services, or component mappings. This prevents
premature architecture commitments or hallucinations before the full scope is
understood.
- **Halting for approval**: For any step where you are instructed
to "obtain approval before proceeding", you MUST stop executing, present the
completed tasks to the user, and wait for their explicit approval. You MUST
NOT proceed to execute any subsequent tasks or generate any further guidance
in that response.
- **Ground all generated content**: For all tasks across all phases, you MUST
first look in the following resources:
- [Product Mapping](references/product-mapping.md),
- [Design Recommendations](references/design-recommendations.md) for the
required guidance. If the guidance does not provide the required information,
you MUST ground the generated content by using the following resources:
- Google Developer Knowledge MCP server:
https://developers.google.com/knowledge/mcp.md.txt
- Server: https://developerknowledge.googleapis.com/mcp
- Tools:
- `developerknowledge:search_documents`
- `developerknowledge:get_documents`
- `developerknowledge:answer_query`
- Relevant skills from https://github.com/google/skills
- Official Google Cloud documentation in
[Related Guidance](references/related-guidance.md)
## Product Renaming & Terminology
When generating solution designs, architecture diagrams, and documentation,
check the latest Google Cloud documentation for the most up-to-date product
names. The table below provides examples of name mappings to be aware of. Note
that underlying APIs, Terraform resources, and IAM roles may retain their legacy
identifiers.
<table>
<thead>
<tr>
<th>Legacy Name</th>
<th>Updated Name</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Vertex AI</td>
<td>Gemini Enterprise Agent Platform</td>
<td>Gemini Enterprise Agent Platform can be shortened to Agent Platform after first instance</td>
</tr>
<tr>
<td>Vertex AI Embedding</td>
<td>Text embedding on Gemini Enterprise Agent Platform</td>
<td>This refers to the text embedding models available on Gemini Enterprise Agent Platform</td>
</tr>
<tr>
<td>Vertex AI Matching Engine</td>
<td>Vector Search</td>
<td></td>
</tr>
</tbody>
</table>
## Phase 1: Requirements discovery
In this phase, you must gather detailed requirements related to the hybrid
search workload that the user wants to design and deploy in Google Cloud.
**Acknowledge provided requirements**: If the
user's prompt already contains some requirements (functional or non-functional,
such as catalog size, search modalities, faceted attributes, or latency
targets), you MUST explicitly acknowledge and restate all of these requirements
in your response. Do NOT ask the user to describe or re-describe any
requirements that they have already provided in the prompt.
Complete the following steps strictly in the specified order:
- [ ] **Step 1**: Ask the user to describe the functional requirements of the
workload, including catalog dataset details (e.g., e-commerce apparel, retail
products, patent database), search modalities (natural language text, visual
search, attribute filters), metadata attributes for faceted filtering (e.g.,
`category`, `sub_category`, `color`, `gender`, `price`), and quality checks
(reranking, LLM validation).
- [ ] **Step 2**: You MUST explicitly ask the user to describe ALL of the
following six categories of non-functional requirements. You need this
information because each category represents a critical architectural pillar,
and neglecting any of them can result in a solution that is insecure,
unreliable, or inefficient (do NOT omit any of them):
- **Security, privacy, and compliance**: E.g., private VPC endpoints, Private
Service Connect, Direct VPC Egress, and access control.
- **Reliability**: E.g., high availability, failover, disaster recovery goals
(RTO/RPO), regional vs multi-region AlloyDB topology.
- **Cost**: E.g., budget constraints for compute, database instances, and
Gemini Enterprise Agent Platform API calls.
- **Operational excellence**: E.g., monitoring, logging, dashboards, and
automated deployment.
- **Performance**: E.g., target P95 query latency (e.g., < 100ms), vector
search recall target (e.g., > 95%), catalog item scale, and QPS
expectations.
- **Sustainability**: E.g., carbon footprint, low-carbon region selection.
- [ ] **Step 3**: Ask the user whether the workload currently runs on other
cloud providers or on-premises.
- If the user's answer is "yes", then ask the user to describe the
architecture of the current deployment.
- If the user's answer is "no", then proceed to the next step.
- [ ] **Step 4**: Ask the user to describe dependencies, if any, on other
workloads, products, or tools (e.g., existing inventory databases, ERP
systems, application runtime languages like Java or Python).
- [ ] **Step 5**: Review the input that the user has provided so far, and check
whether there are any ambiguities, conflicts, or contradictions in the
functional requirements, non-functional requirements, and dependencies. You
MUST compare all requirements against each other to identify any conflicts.
If you identify any ambiguities, conflicts, or contradictions in the
requirements that the user has provided, you MUST do the following for each
ambiguity, conflict, or contradiction:
- [ ] Identify exactly where each contradiction lies and explain to the
user why the requirements are incompatible and cannot be simultaneously
satisfied. Do NOT treat fundamental contradictions as design choice
questions (e.g., asking how to implement or configure a conflicting
requirement).
- [ ] Ask the user to clarify their trade-off preferences to resolve the
contradiction.
- [ ] If the user delegates the choice to you (e.g., the user replies with
"do what you think is best" or "you decide"), then provide a clear
suggestion to resolve the ambiguity or contradiction, explain your
reasoning, and ask the user to approve your suggestion.
**Critical**: Until all the ambiguities and contradictions that you identify
are resolved according to the preceding guidance, you must NOT recommend or
generate any architecture design or Google Cloud product recommendations.
- [ ] **Step 6**: Summarize the functional and non-functional requirements
provided by the user into a consolidated requirements summary.
- [ ] **Step 7**: Present the generated requirements summary to the user and
obtain approval (the user MUST explicitly say "yes" or "I approve") before
proceeding to Phase 2.
**Important**: **STOP**, DON'T proceed to generate architecture diagram,
architecture description or product recommendations until you have confirmed the
generated requirements summary and resolved all ambiguities and contradictions
in this phase.
## Phase 2: Solution architecture
### Task 2.1: Identify Google Cloud products and features required for the workload.
- [ ] **Step 1**: Recommend products and features that are appropriate for each
component of the user's workload, prioritizing Google Cloud products.
**Important**: The Google Cloud products and features that you recommend
MUST be consistent with the guidance in
[Product Mapping](references/product-mapping.md).
- [ ] **Step 4**: Present the generated product recommendations to the user and
obtain approval (the user MUST explicitly say "yes" or "I approve") before
proceeding to Task 2.2.
**Important**: **STOP**, DON'T proceed to generate architecture diagram until
you have confirmed the generated product recommendations with the user.
### Task 2.2: Generate an architecture diagram and description
- [ ] **Step 1**: Generate an architecture diagram in the Mermaid format:
https://github.com/mermaid-js/mermaid.
The diagram must show the data flows and request flows across the components
of the architecture, based on the gathered requirements and product
recommendations. The diagram MUST explicitly show both the ingestion pipeline
and serving pipeline.
The following is an **example** of the data flows and request flows that the
architecture diagram should show:
- **Ingestion pipeline**: Catalog Data -> AlloyDB Table
(`apparels`) -> B-Tree Indexes on Facets -> Text embedding
(`text-embedding-005`) -> ScaNN Vector Index.
- **Serving pipeline**: User Browser -> Cloud Run Web App -> MCP
Toolbox for Databases -> AlloyDB Single-Query Hybrid Search (ScaNN Vector
Search + SQL WHERE Filters) -> `ai.rank` Reranker -> Gemini Pro
`ai.generate` Quality Validation -> Validated Results -> User Browser.
- [ ] **Step 2**: Generate a description that explains the purpose of each
component, the relationships between the components, and the task flow or data
flow.
- [ ] **Step 3**: Present the generated architecture diagram and description
to the user and obtain approval (the user MUST explicitly say "yes" or "I
approve") before proceeding to Task 2.3.
**Important**: **STOP**, DON'T proceed to generate design recommendations
until you have confirmed the generated architecture description with the user.
### Task 2.3: Generate design recommendations.
- [ ] **Step 1**: Generate design recommendations and best practices to
optimally configure each component in the architecture based on the workload
requirements.
**Important**:
- When you generate design recommendations, consider the following:
- Functional requirements that were gathered in Phase 1.
- Non-functional requirements that were gathered in Phase 1.
- Align the generated design recommendations with the recommendations in
[Design Recommendations](references/design-recommendations.md).
- To generate guidance for the non-functional requirements, use the
following skills:
- `google-cloud-waf-security`
- `google-cloud-waf-reliability`
- `google-cloud-waf-cost-optimization`
- `google-cloud-waf-operational-excellence`
- `google-cloud-waf-performance-optimization`
- `google-cloud-waf-sustainability`
- [ ] **Step 2**: Present the generated recommendations to the user and obtain
approval (the user MUST explicitly say "yes" or "I approve") before
proceeding to Task 2.4.
**Important**: **STOP**, DON'T proceed to generate deployment guidance until
you have confirmed the design recommendations with the user.
### Task 2.4: Generate deployment guidance.
- [ ] **Step 1**: Generate guidance to deploy the solution, including the
following:
- AlloyDB DDL & SQL setup scripts for extensions (`google_ml_integration`,
`alloydb_scann`), tables, B-Tree indexes, ScaNN vector indexes, hybrid
search SQL, and Gemini validation CTEs.
- MCP Toolbox deployment configuration on Cloud Run.
- Python Cloud Run Function shim deployment command.
- Application deployment command (`gcloud run deploy {app_name}`).
- Terraform code or `gcloud` CLI commands to create required infrastructure.
**Important**: The deployment guidance that you generate MUST be consistent
with the guidance in the following resources:
- [Related Guidance](references/related-guidance.md)
- Relevant skills in
https://github.com/google/skills/tree/main/skills/cloud
- [ ] **Step 2**: Present the generated deployment guidance to the user and
obtain approval (the user MUST explicitly say "yes" or "I approve") before
proceeding to Phase 3.
**Important**: **STOP**, DON'T proceed to generate solution validation until
you have confirmed the deployment guidance with the user.
## Phase 3: Solution validation
### Task 3.1: Pre-deployment validation
- [ ] **Step 1**: Create a pre-deployment plan to statically validate the
generated solution and verify that it meets the workload requirements
without provisioning live resources:
- **Deployment dry-run**: Validate infrastructure syntax and preview the
resources that will be provisioned using dry-run commands (e.g.,
`terraform plan` or (where supported) `gcloud ... --dry-run`).
- **Architecture & policy analysis**: Perform static verification of
network routing topologies, firewall rules, and IAM enforcement against
best practices.
- [ ] **Step 2**: Present the static validation plan to the user, obtain
approval (the user MUST explicitly say "yes" or "I approve"), and execute the
dry-run commands.
- [ ] **Step 3**: Troubleshoot and fix any errors or policy discrepancies
identified during dry-run checks until validation succeeds.
- [ ] **Step 4**: Proceed to Task 3.2
### Task 3.2: Runtime validation (Post-deployment)
- [ ] **Step 1**: Ask the user whether they choose to deploy the infrastructure
now to perform live runtime verification, or skip directly to Phase 4.
- [ ] **Step 2**: **If the user chooses to deploy the infrastructure**:
- After the user deploys the infrastructure, generate runtime
verification commands (using tools like `curl`, `ping`, or `gcloud`)
and provide them to the user to execute, to test live endpoint
reachability, networking paths, and load balancer routing.
- Troubleshoot any deployment or runtime routing issues until checks pass.
- [ ] **Step 3**: Proceed to Phase 4.
## Phase 4: Solution packaging and presentation
- [ ] **Step 1**: Consolidate the final text artifacts that were generated in
Phase 2 into a single Markdown file named `solution-architecture-guide.md`,
based on the template in [Output Template](assets/output-template.md).
- [ ] **Step 2**: Request the user's permission to write the code files in the
user's workspace.
- [ ] **Step 3**: After the user gives permission, write the final code files in
the user's workspace.
output-template.md 7.2 KB
<!-- Use this template to compile the content that you generate based on the
instructions in `SKILL.md`. -->
# Google Cloud solution architecture: Hybrid Search
## 1. Executive summary and workload overview
[A brief description of the workload, its business goals, and the high-level
solution architecture proposed.]
## 2. Requirements and current state
### 2.1. Functional requirements
- **Business processes**: [Details of the business processes supported]
- **Activities and use cases**: [Details of the key activities and use cases]
### 2.2. Non-functional requirements
- **Security**: [Details of the security requirements including compliance,
encryption, access control requirements]
- **Reliability**: [Details of the reliability requirements including SLA,
RTO/RPO, backup, redundancy requirements]
- **Cost**: [Details of the cost constraints and pricing models]
- **Operations**: [Details of the operational requirements including
monitoring, logging, deployment, maintenance requirements]
- **Performance**: [Details of the performance requirements including latency,
throughput, scaling requirements]
- **Sustainability**: [Details of the sustainability requirements including
carbon footprint, resource optimization requirements]
### 2.3. Current state
[If applicable, describe the current on-premises or other-cloud architecture.]
- **Current infrastructure**: [Details of existing setup]
- **Pain points and drivers for migration/redesign**: [Details of the drivers
for migration/redesign]
### 2.4. Dependencies
- **Internal dependencies**: [Details of internal dependencies including other
workloads and internal services]
- **External dependencies**: [Details of external dependencies including
third-party products and on-premises tools]
## 3. Technical decomposition of the workload
[Technical decomposition of the workload components, breaking down the
application into logical layers: data ingestion & embedding pipeline, relational
& vector data store, hybrid query engine & reranker, database abstraction &
agentic tooling, and web application UI.]
## 4. Proposed solution architecture
### 4.1. Google Cloud products and features mapping
[Identify Google Cloud products and features mapped to the technical
components. For each component, justify the selection, note alternatives
considered, and describe the pros and cons of the recommended product/feature
and alternatives.]
| Component | Recommended Google Cloud product/feature | Justification and citations | Alternatives considered | Pros and cons of alternatives |
| :------------------- | :--------------------------------------- | :------------------------------------------------- | :---------------------- | :------------------------------- |
| **[Component Name]** | **[Product Name]** | [Why this product is chosen, citing official docs] | [Alternative product] | **Pros**: ... <br> **Cons**: ... |
### 4.2. Architecture diagram
[Architecture diagram in Mermaid format showing the relationships and flows
between the components of the architecture.]
```mermaid
%% Example hybrid search topology
graph TD
User([User Browser]) --> LoadBalancer[Application Load Balancer]
LoadBalancer --> WebApp[Cloud Run Web App]
WebApp --> MCPToolbox[MCP Toolbox for Databases]
MCPToolbox --> AlloyDB[(AlloyDB for PostgreSQL)]
subgraph AlloyDB for PostgreSQL
AlloyDB -->|Embedding Generation| GeminiEnterpriseAgentPlatform[Agent Platform text-embedding-005]
AlloyDB -->|ScaNN Vector Search| ScaNNIndex[ScaNN Index Scan]
AlloyDB -->|In-Database LLM Reranking| Gemini[ Gemini AI Operators]
end
```
### 4.3. Architecture description
[Detailed description of the architecture. Describe the task flow and data
flow between the components of the architecture.]
- **Data flow**: [Describe the flow of data.]
- **Tasks/control flow**: [Describe the flow of tasks/control.]
## 5. Design and configuration recommendations
[Best practices and configuration recommendations for each pillar of the
Google Cloud Architecture Framework.]
### 5.1. Security, privacy, and compliance
* **Access control**: [E.g., IAM least privilege roles (roles/alloydb.client, roles/aiplatform.user), PostgreSQL database-native CREATE ROLE permissions, search_path isolation]
* **Data protection**: [E.g., CMEK encryption at rest, mTLS Auth Proxy transit encryption, DLP de-identification templates]
* **Network Security**: [E.g., Direct VPC Egress, Private Services Access/PSC, Cloud Armor WAF rules, disabled default run.app URLs]
### 5.2. Reliability
* **Redundant deployment**: [E.g., AlloyDB multi-zone HA instance, regional Cloud Run deployment]
* **Backup and DR**: [E.g., AlloyDB continuous microsecond PITR backups, cross-region replication]
### 5.3. Operational excellence
* **Monitoring and logging**: [E.g., Cloud Logging structured JSON logs, Cloud Trace, AlloyDB Query Insights and System Insights dashboards]
* **Infrastructure as Code (IaC)**: [E.g., Terraform manifests, gcloud CLI commands]
### 5.4. Cost optimization
* **Sizing and scaling**: [E.g., Cloud Run scale-to-zero, Cloud Storage Object Lifecycle Management]
* **Pricing models**: [E.g., Committed Use Discounts (CUDs) for AlloyDB compute]
### 5.5. Performance efficiency
* **Caching and database indexing**: [E.g., ScaNN multi-level tree tuning (num_leaves, num_leaves_to_search), B-tree facet indexes, leaf search streaming (scann.satisfy_limit = 'relaxed_order')]
* **Data updates**: [E.g., Automated embedding generation, automatic ScaNN index self-maintenance (`MODE='AUTO'`)]
### 5.6. Sustainability
* [E.g., Serverless compute scaling, in-database query execution and AI function evaluation]
## 6. Deployment guidance
[Instructions and code for deploying the architecture.]
### 6.1. Deployment prerequisites
* [Prerequisite 1: E.g., Enabling APIs (alloydb.googleapis.com, aiplatform.googleapis.com, run.googleapis.com)]
* [Prerequisite 2: E.g., Installing SDKs/tools (gcloud, terraform, psql)]
* ...and so on
### 6.2. Step-by-step deployment instructions
1. [Step 1: E.g., Authenticate with Google Cloud and set project environment]
2. [Step 2: E.g., Initialize and apply Terraform infrastructure manifests]
3. [Step 3: E.g., Deploy containerized application and MCP tools to Cloud Run]
## 7. Validation plan
[Details of the pre-deployment static dry-run checks and post-deployment runtime
verification steps (e.g., ScaNN vector query recall measurement using
evaluate_query_recall, endpoint health checks).]
## 8. References
- [E.g., Secure agent interactions with MCP Toolbox for Databases](https://docs.cloud.google.com/alloydb/docs/ai/secure-agent-interactions-mcp)
- [E.g., RAG infrastructure for generative AI using Agent Platform and AlloyDB for PostgreSQL](https://docs.cloud.google.com/architecture/rag-capable-gen-ai-app-using-vertex-ai)
- [E.g., Best practices for tuning ScaNN index in AlloyDB](https://docs.cloud.google.com/alloydb/docs/ai/best-practices-tuning-scann)
- [E.g., Choose a connectivity option for AlloyDB](https://docs.cloud.google.com/alloydb/docs/choose-alloydb-connectivity)
- [E.g., AlloyDB security best practices](https://docs.cloud.google.com/alloydb/docs/security-best-practices)
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-solution-hybrid-search-alloydb)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:google-cloud-solution-hybrid-search-alloydb)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-solution-hybrid-search-alloydb)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
design-recommendations.md 5.9 KB
# Design recommendations
Important: The recommendations below apply to the primary recommended products
in `references/product-mapping.md`. If an alternative product is selected,
use the resources listed under that product's section in
`references/product-mapping.md` to generate appropriate design
recommendations.
Use the following guidance to generate design recommendations for a secure,
scalable, and high-performance hybrid search solution combining structured
relational queries, full-text search, and vector similarity search on Google
Cloud.
* **Security, privacy, and compliance**:
* Encrypt AlloyDB database data at rest using Customer-Managed Encryption
Keys (CMEK) and restrict network access by creating a service perimeter
with VPC Service Controls (VPC-SC).
* Combine IAM least-privilege roles (`roles/alloydb.client`,
`roles/alloydb.viewer`) with PostgreSQL database-native granular roles
(`CREATE ROLE`) to prevent destructive commands (such as `DROP TABLE` or
`TRUNCATE`) even if an agent identity is compromised.
* Use AlloyDB Auth Proxy or Language Connectors for IAM-based connection
authorization and TLS 1.3 encrypted data transit.
* Prevent PostgreSQL search path hijacking by setting `ALTER ROLE
user_name SET search_path = pg_catalog, pg_temp;` for privileged
database roles to bypass untrusted public schemas.
* Disable default `run.app` ingress URLs for Cloud Run services, routing
public traffic exclusively through a regional external Application Load
Balancer protected by Cloud Armor WAF rules (`sqli-v33-stable` and XSS
protection).
* Mitigate multi-tenant prompt injection data leaks by deploying specific
custom tools (e.g., `lookup_active_order` via MCP Toolbox) where tenant
identity filters are enforced in backend code outside LLM prompt
control, avoiding generic open-ended `execute_sql` access.
* Enforce action-selection patterns (hardcoded Action-Selector or Dual-LLM
guardrail pre-screening) and strict tool allowlists to prevent
unauthorized tool chaining and control-flow manipulation.
* Enable Model Armor on AI endpoints (`gcloud ai endpoints update
--enable-model-armor`) to sanitize MCP tool inputs and outputs, and
configure Sensitive Data Protection (DLP) de-identification templates
(`model_armor_config.json`) to redact PII automatically.
* Enable Data Access audit logging in Cloud Logging for MCP tools and
AlloyDB services, logging raw LLM SQL commands, tool parameters, user
IDs, and session IDs to detect exfiltration attempts via log-based
alerts.
* **Reliability**:
* Provision AlloyDB primary instances with automatic multi-zone high
availability (HA) failover and configure microsecond Point-In-Time
Recovery (PITR) continuous backups to recover from accidental or
malicious data corruption by autonomous agents.
* Deploy Cloud Run web services and shims across multiple availability
zones within a region to ensure automatic load-balancing and zone outage
resilience.
* Use regional or dual-region Cloud Storage buckets combined with Pub/Sub
message flow control and retry policies to handle ingestion spikes
reliably.
* **Operational excellence**:
* To minimize recall degradation and reduce manual interventions,
configure ScaNN vector indexes with automatic maintenance enabled.
* Use AlloyDB Query Insights and System Insights dashboards to monitor
query latency, replication lag, and peak database connection counts.
* Route application logs to Cloud Logging in structured JSON format and
trace complete end-to-end execution paths across services using Cloud
Trace.
* **Cost optimization**:
* Utilize Committed Use Discounts (CUDs) for predictable AlloyDB instance
compute workloads, or basic instances for non-production development
environments.
* Configure Cloud Run services to scale to zero instances when idle to
eliminate compute costs during off-peak hours.
* Apply Object Lifecycle Management policies to Cloud Storage buckets to
automatically archive or delete temporary ingestion data.
* Configure Cloud Logging exclusion filters to drop non-critical debug
logs and reduce log storage costs.
* **Performance efficiency**:
* Configure ScaNN index parameters based on dataset size and tree depth:
* *Two-Level Tree*: Set `num_leaves = sqrt(rows)` for balanced build
speed, or `rows/100` for optimal quality.
* *Three-Level Tree*: Set `max_num_levels = 2` and
`num_leaves =power(rows, 2/3)` (balanced) or `rows/100` (quality).
* *Four-Level Tree*: Set `scann.max_allowed_num_levels = 3`,
`max_num_levels = 3`, and `num_leaves = power(rows, 3/4)`.
* Improve search recall on highly selective filters by setting
`scann.satisfy_limit = 'relaxed_order'` (streaming) and capping
partition search using `scann.max_num_leaves_to_search_pct = 15`.
* For high-dimensional embeddings (>= 500 dimensions), tune
`scann.pre_reordering_num_neighbors` (default `50 * K`) to refine
re-ranking precision.
* Attach Direct VPC Egress to Cloud Run services to establish low-latency,
private IP network paths to the AlloyDB instance without internet hops.
* **Sustainability**:
* Utilize serverless compute platforms (Cloud Run and Cloud Run functions)
to automatically scale compute down when idle, minimizing energy
consumption.
* Execute vector distance calculations, full-text ranking, and embedding
generation directly inside AlloyDB to avoid unnecessary cross-service
network egress and duplicate compute cycles.
product-mapping.md 10.7 KB
# Product Mapping Guidance for Hybrid Search Solutions
Use the guidance in this file to do the following:
- Recommend appropriate products and features for the components of the hybrid
search system
- Explain the rationale and trade-offs for each recommendation.
| Component | Product / Architecture Option | Line hints |
|-----------|--------------------------------|------------|
| [Database & Vector Search Store](#database-vector-search-store) | [AlloyDB for PostgreSQL (AlloyDB AI)](#alloydb-for-postgresql-alloydb-ai) (Primary) | Lines 24-39 |
| [Database & Vector Search Store](#database-vector-search-store) | [BigQuery Vector Search](#bigquery-vector-search) (Alt 1) | Lines 41-67 |
| [Database & Vector Search Store](#database-vector-search-store) | [Cloud SQL](#cloud-sql) (Alt 2) | Lines 69-86 |
| [Vector Embeddings Engine](#vector-embeddings-engine) | [Text embeddings on Gemini Enterprise Agent Platform](#text-embeddings-on-gemini-enterprise-agent-platform) (Primary) | Lines 90-98 |
| [Vector Embeddings Engine](#vector-embeddings-engine) | [Self-hosted embedding model](#self-hosted-embedding-model) (Alt 1) | Lines 100-109 |
| [Database Abstraction & Agentic Tooling](#database-abstraction-agentic-tooling) | [MCP Toolbox for Databases](#mcp-toolbox-for-databases) (Primary) | Lines 113-124 |
| [Database Abstraction & Agentic Tooling](#database-abstraction-agentic-tooling) | [Managed Google Cloud Remote MCP Servers](#managed-google-cloud-remote-mcp-servers) (Alt 1) | Lines 126-139 |
| [Database Abstraction & Agentic Tooling](#database-abstraction-agentic-tooling) | [Remote Custom MCP Servers Hosted on Cloud Run](#remote-custom-mcp-servers-hosted-on-cloud-run) (Alt 2) | Lines 141-152 |
| [Web Application Hosting](#web-application-hosting) | [Cloud Run](#cloud-run) (Primary) | Lines 156-165 |
| [Networking & Security Topology](#networking-security-topology) | [Regional External Application Load Balancer and Direct VPC Egress](#regional-external-application-load-balancer-and-direct-vpc-egress) (Primary) | Lines 169-177 |
## <a id="database-vector-search-store"></a>Database & Vector Search Store
### <a id="alloydb-for-postgresql-alloydb-ai"></a>Primary Recommendation: AlloyDB for PostgreSQL (AlloyDB AI)
* **Description**: Fully managed, PostgreSQL-compatible relational database
designed for demanding enterprise workloads, equipped with built-in ScaNN
vector indexing and Gemini Enterprise Agent Platform integration using
`google_ml_integration`.
* **Advantages**:
* ScaNN index algorithm delivers up to 4x faster vector search queries
than standard HNSW/IVFFlat at high recall.
* In-database vector embeddings (`embedding('text-embedding-005', ...)`),
reranking (`ai.rank`), and LLM calls (`ml_predict_row`) eliminate data
movement outside the database boundary.
* Integrated `evaluate_query_recall` function provides automated,
in-database accuracy measurement.
* Single SQL query seamlessly combines vector similarity ordering with
structured relational filters (`WHERE category = ANY(...)`).
### <a id="bigquery-vector-search"></a>Alternative 1: BigQuery Vector Search
* **Description**: Enterprise data warehouse and lakehouse platform featuring
native hybrid search (`AI.SEARCH` with `mode => 'HYBRID'`, and
`VECTOR_SEARCH` with `lexical_search_columns`), batch embedding generation
(`AI.GENERATE_EMBEDDING`), autonomous background embeddings (`AI.EMBED`),
and ScaNN (`TREE_AH`) / IVF vector indexing (`CREATE VECTOR INDEX`).
* **Advantages**:
* Scales to billions of rows across structured tables, unstructured
documents (`ObjectRef`), and data lakehouses without infrastructure
management.
* Provides native SQL hybrid search functions: `AI.SEARCH` (TVF combining
vector similarity with lexical search on autonomous embedding tables)
and `VECTOR_SEARCH` (with `lexical_search_columns`).
* Accelerates hybrid search with `CREATE VECTOR INDEX` supporting ScaNN
(`TREE_AH`) and Inverted File (`IVF`) algorithms with `STORING` clauses
for metadata pre-filtering and join elimination.
* Includes Gemini in BigQuery for AI-assisted data exploration,
conversational analytics with custom data agents, automated data
insights, and natural language SQL/Python code generation.
* Supports both batch embedding generation across very large tables via
`AI.GENERATE_EMBEDDING` (TVF) and continuous autonomous maintenance via
`AI.EMBED` stored generated columns.
* Ideal for gigabyte to petabyte-scale analytical RAG, log analytics,
audience segmentation, and batch hybrid search entirely in standard SQL
(vs low-latency transactional OLTP in AlloyDB).
* **Resources** (Only put into context if the user selects this alternative
product):
* `https://docs.cloud.google.com/bigquery/docs/vector-search-intro.md.txt`
* `https://docs.cloud.google.com/bigquery/docs/gemini-overview.md.txt`
* `https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-ai-search.md.txt`
* `https://docs.cloud.google.com/bigquery/docs/vector-index.md.txt`
### <a id="cloud-sql"></a>Alternative 2: Cloud SQL
* **Description**: Fully managed relational database service offering native
vector search (`VECTOR` data type, ScaNN `TREE_SQ` indexing,
`approx_distance` and `vector_distance` functions) for MySQL, and `pgvector`
for PostgreSQL.
* **Advantages**:
* Lower entry cost and simpler operational setup for small to medium
workloads (less than 10M rows).
* Fully transactionally consistent, real-time ACID-compliant vector index
updates during DML operations.
* Supports ScaNN algorithm and iterative filtering
(`cloudsql_vector_iterative_filtering`) for ANN similarity queries in
Cloud SQL for MySQL.
* **Resources** (Only put into context if the user selects this alternative
product):
* `https://docs.cloud.google.com/sql/docs/mysql/vector-search.md.txt`
* `https://docs.cloud.google.com/sql/docs/mysql/integrate-cloud-sql-with-vertex-ai.md.txt`
## <a id="vector-embeddings-engine"></a>Vector Embeddings Engine
### <a id="text-embeddings-on-gemini-enterprise-agent-platform"></a>Primary Recommendation: Text embeddings on Gemini Enterprise Agent Platform
* **Description**: Managed text embedding model producing 768-dimensional
dense vector representations optimized for semantic search and retrieval.
* **Advantages**:
* Directly invocable from SQL inside AlloyDB, BigQuery, and Cloud SQL.
* High semantic accuracy across multi-lingual and domain-specific retail
search queries.
* Fully managed scaling and zero model server maintenance.
### <a id="self-hosted-embedding-model"></a>Alternative 1: Self-hosted embedding model
* **Description**: Custom-deployed open-source or fine-tuned text embedding
model hosted on Cloud Run or Gemini Enterprise Agent Platform.
* **Advantages**: Complete control over customized fine-tuned open-source models.
* **Resources** (Only put into context if the user selects this alternative
product):
* `https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-garden/self-deployed-models.md.txt`
* `https://docs.cloud.google.com/run/docs/deploying.md.txt`
## <a id="database-abstraction-agentic-tooling"></a>Database Abstraction & Agentic Tooling
### <a id="mcp-toolbox-for-databases"></a>Primary Recommendation: MCP Toolbox for Databases
* **Description**: Model Context Protocol (MCP) Toolbox is an open source
Model Context Protocol (MCP) server that connects your AI agents, IDEs, and
applications directly to your enterprise databases.
* **Advantages**:
* Decouples database execution and complex hybrid search SQL logic from
application code.
* Exposes clean REST/MCP tool endpoints for AI agents and application
services.
* Supports agentic tool integration out of the box with custom tools that
enforce tenant isolation boundaries.
### <a id="managed-google-cloud-remote-mcp-servers"></a>Alternative 1: Managed Google Cloud Remote MCP Servers
* **Description**: Fully managed remote MCP servers provided by Google Cloud
(managed via Agent Registry) offering built-in IAM governance, Model Armor
security scanning, and pre-packaged toolsets for Google Cloud services.
* **Advantages**:
* Zero server infrastructure management; built-in IAM authentication,
fine-grained access policies, and Model Armor prompt injection
protection.
* Exposes tools, prompts, and resources via standardized MCP discovery
(`tools/list`).
* **Resources** (Only put into context if the user selects this alternative
product):
* `https://docs.cloud.google.com/mcp/overview.md.txt`
### <a id="remote-custom-mcp-servers-hosted-on-cloud-run"></a>Alternative 2: Remote Custom MCP Servers Hosted on Cloud Run
* **Description**: Custom MCP servers built using open-source SDKs
(TypeScript, Python, Go, FastMCP) deployed on Cloud Run using streamable
HTTP or Server-Sent Events (SSE) transport.
* **Advantages**:
* Complete flexibility to implement custom tools, prompts, and resources
tailored to hybrid search applications.
* Supports serverless auto-scaling, sidecar deployment alongside AI
agents, and service-to-service IAM authentication (`roles/run.invoker`).
* **Resources** (Only put into context if the user selects this alternative
product):
* `https://docs.cloud.google.com/run/docs/host-mcp-servers.md.txt`
## <a id="web-application-hosting"></a>Web Application Hosting
### <a id="cloud-run"></a>Primary Recommendation: Cloud Run
* **Description**: Fully managed serverless container platform that
automatically scales compute instances based on incoming traffic.
* **Advantages**:
* Scales to zero when idle; seamlessly handles traffic bursts.
* Native integration with Direct VPC Egress for secure private connection
to AlloyDB.
* Supports any containerized web framework (Java Spring Boot, Python
FastAPI, Node.js).
## <a id="networking-security-topology"></a>Networking & Security Topology
### <a id="regional-external-application-load-balancer-and-direct-vpc-egress"></a>Primary Recommendation: Regional External Application Load Balancer and Direct VPC Egress
* **Description**: Edge load balancer providing Cloud Armor DDoS/WAF
protection, routing traffic to Cloud Run services configured with Direct VPC
Egress to communicate with AlloyDB over private IP ranges.
* **Advantages**:
* Strict physical and network isolation for database tier.
* Cloud Armor protection against SQL injection and web threats.
related-guidance.md 2.6 KB
Use these documents to help inform the creation of a Google Cloud hybrid search
architecture and deployment:
## Architecture and design guidance
- [Secure agent interactions with MCP Toolbox for Databases](https://docs.cloud.google.com/alloydb/docs/ai/secure-agent-interactions-mcp.md.txt):
Information on configuring security, connection management, and agent
interaction boundaries using MCP Toolbox for Databases.
- [RAG infrastructure for generative AI using Agent Platform and AlloyDB for PostgreSQL](https://docs.cloud.google.com/architecture/rag-capable-gen-ai-app-using-vertex-ai.md.txt):
An architecture that stores vector embeddings alongside your operational
data in a fully managed database like AlloyDB for PostgreSQL.
- [Best practices for tuning ScaNN index in AlloyDB](https://docs.cloud.google.com/alloydb/docs/ai/best-practices-tuning-scann.md.txt):
Best practices for tuning ScaNN index parameters like num_leaves,
num_leaves_to_search, and pre_reordering_num_neighbors for high recall and
fast query performance.
- [Choose a connectivity option for AlloyDB](https://docs.cloud.google.com/alloydb/docs/choose-alloydb-connectivity.md.txt):
Compares AlloyDB connectivity methods, including AlloyDB Auth Proxy, Private
Service Connect (PSC), and direct VPC peering.
- [AlloyDB security best practices](https://docs.cloud.google.com/alloydb/docs/security-best-practices.md.txt):
Recommendations to secure AlloyDB instances using IAM database
authentication, Private Service Connect, and VPC perimeters.
## Deployment
- [Hybrid search on Cloud Run codelab](https://codelabs.developers.google.com/hybrid-search-on-cloudrun#0):
A step-by-step hands-on tutorial for building and deploying a hybrid search
application using AlloyDB, Gemini Enterprise Agent Platform, and Cloud Run.
- [Run hybrid vector similarity search in AlloyDB](https://docs.cloud.google.com/alloydb/docs/ai/run-hybrid-vector-similarity-search.md.txt):
Guidance to construct and execute hybrid search queries combining vector
similarity ordering with relational SQL filtering in AlloyDB
- [Evaluate semantic queries using AI operators in AlloyDB](https://docs.cloud.google.com/alloydb/docs/ai/evaluate-semantic-queries-ai-operators.md.txt):
Guidance to use in-database AI functions such as ml_predict_row and ai.rank
for semantic reranking and LLM validation.
- [Cloud Run Direct VPC Egress](https://docs.cloud.google.com/run/docs/configuring/vpc-direct-vpc.md.txt):
Instructions to set up Direct VPC Egress for Cloud Run services to access
private resources like AlloyDB within a VPC network.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE