Skip to content

feat(spanner): Add hybrid full-text and vector RRF search sample - #14847

Open
iennae wants to merge 3 commits into
mainfrom
feat/spanner-hybrid-search-rrf
Open

iennae wants to merge 3 commits into
mainfrom
feat/spanner-hybrid-search-rrf

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Hybrid retrieval in Cloud Spanner fuses keyword precision (SEARCH / SCORE) with semantic vector recall (COSINE_DISTANCE) inside a single SQL query using Reciprocal Rank Fusion (1 / (k + rank)), requiring simultaneous STRING and ARRAY<FLOAT32> parameter bindings.

Adds spanner_hybrid_search_rrf executing a single-round-trip hybrid RRF query from Python.

Note: Stacked on #14836 (feat/spanner-vector-search-knn) so this PR shows only this sample's diff. It will merge into main after #14836.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Python developers implementing semantic similarity search on Cloud Spanner lacked a client library example showing parameterized FLOAT32 vector bindings with COSINE_DISTANCE.
Combining lexical full-text search and semantic vector similarity with Reciprocal Rank Fusion in a single Cloud Spanner query lacked a runnable Python example.
@iennae
iennae requested review from a team as code owners November 17, 2026 18:48
@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 17, 2026
@snippet-bot

snippet-bot Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new script, hybrid_search_rrf.py, which implements hybrid search in Google Cloud Spanner by combining full-text and vector search using Reciprocal Rank Fusion (RRF), along with a comprehensive test suite in hybrid_search_rrf_test.py. The feedback recommends enhancing the script's flexibility by allowing the Google Cloud project ID to be automatically inferred from Application Default Credentials (ADC) when not explicitly provided. This involves making the project_id parameter optional, resolving it via the Spanner client, updating error messages to use the resolved ID, and adjusting the command-line argument parser. Additionally, the reviewer suggests mocking the project attribute on the Spanner client throughout the unit tests to ensure consistent and clean test execution.

Comment on lines +23 to +33
def run_hybrid_search_rrf(project_id: str, instance_id: str, database_id: str) -> None:
"""Combines full-text and ANN vector search via Reciprocal Rank Fusion.

Args:
project_id: The Google Cloud project ID.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems,
CatalogEmbeddingIndex, and CatalogSearchIndex.
"""
client = spanner.Client(project=project_id)
database = client.instance(instance_id).database(database_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To allow the project ID to be automatically inferred from Application Default Credentials (ADC) when not explicitly provided, update the project_id parameter to be optional (str | None) and resolve the actual project ID using client.project.

Suggested change
def run_hybrid_search_rrf(project_id: str, instance_id: str, database_id: str) -> None:
"""Combines full-text and ANN vector search via Reciprocal Rank Fusion.
Args:
project_id: The Google Cloud project ID.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems,
CatalogEmbeddingIndex, and CatalogSearchIndex.
"""
client = spanner.Client(project=project_id)
database = client.instance(instance_id).database(database_id)
def run_hybrid_search_rrf(
project_id: str | None, instance_id: str, database_id: str
) -> None:
"""Combines full-text and ANN vector search via Reciprocal Rank Fusion.
Args:
project_id: The Google Cloud project ID.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems,
CatalogEmbeddingIndex, and CatalogSearchIndex.
"""
client = spanner.Client(project=project_id)
resolved_project_id = client.project
database = client.instance(instance_id).database(database_id)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +93 to +104
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"in project '{project_id}' was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: hybrid RRF search failed on database '{database_id}' "
f"in instance '{instance_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the error messages to use resolved_project_id instead of project_id so that the actual resolved project ID is printed when project_id is inferred from ADC.

Suggested change
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"in project '{project_id}' was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: hybrid RRF search failed on database '{database_id}' "
f"in instance '{instance_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"in project '{resolved_project_id}' was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: hybrid RRF search failed on database '{database_id}' "
f"in instance '{instance_id}' for project '{resolved_project_id}': {err.message}",
file=sys.stderr,
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +123 to +127
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In accordance with the general rules, the --project-id argument should be optional and default to None (or os.environ.get("GOOGLE_CLOUD_PROJECT") without a fallback string) so that the project can be inferred from Application Default Credentials (ADC) if not provided.

Suggested change
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +35 to +39
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Mock the project attribute on the Spanner client to ensure the tests use the expected project ID and avoid printing MagicMock representations in error logs.

Suggested change
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value
client = mock_client_class.return_value
client.project = PROJECT_ID
database = client.instance.return_value.database.return_value
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +79 to +83
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
snapshot = database.snapshot.return_value.__enter__.return_value
snapshot.execute_sql.side_effect = error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Mock the project attribute on the Spanner client in the error tests as well to ensure consistent behavior and clean output.

Suggested change
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
snapshot = database.snapshot.return_value.__enter__.return_value
snapshot.execute_sql.side_effect = error
client = mock_client_class.return_value
client.project = PROJECT_ID
database = client.instance.return_value.database.return_value
snapshot = database.snapshot.return_value.__enter__.return_value
snapshot.execute_sql.side_effect = error

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +98 to +102
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Mock the project attribute on the Spanner client in the CLI entrypoint test to ensure consistent behavior.

Suggested change
database = (
mock_client_class.return_value.instance.return_value.database.return_value
)
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value
client = mock_client_class.return_value
client.project = PROJECT_ID
database = client.instance.return_value.database.return_value
database.name = DATABASE_NAME
snapshot = database.snapshot.return_value.__enter__.return_value

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Prints short resource identifiers instead of full project-prefixed resource paths and omits project_id from diagnostic messages.
Base automatically changed from feat/spanner-vector-search-knn to main December 1, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants