Skip to content

feat(spanner): Add ranked full-text SEARCH and SCORE sample - #14846

Open
iennae wants to merge 3 commits into
mainfrom
feat/spanner-full-text-search
Open

iennae wants to merge 3 commits into
mainfrom
feat/spanner-full-text-search

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Cloud Spanner full-text search guides demonstrate SEARCH and relevance ranking (SCORE) in SQL, leaving Python developers without a reference for parameterized query execution against a SEARCH INDEX.

Adds spanner_full_text_search binding user query strings via param_types.STRING and ordering matching documents by SCORE.

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.
Full-text search guides for Cloud Spanner show SQL queries using SEARCH and SCORE without a Python sample binding user search queries safely as parameters.
@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 module full_text_search.py that implements ranked full-text search queries in Google Cloud Spanner, along with a comprehensive test suite. The review feedback suggests making the project_id parameter optional to leverage Application Default Credentials (ADC) for automatic project inference. This includes updating the function signature, using client.project in error logs, adjusting the command-line argument defaults, and updating the mock-based unit tests to set the expected project attribute.

Comment on lines +23 to +33
def run_full_text_search(project_id: str, instance_id: str, database_id: str) -> None:
"""Executes a parameterized full-text SEARCH() query ranked by SCORE().

Args:
project_id: The Google Cloud project ID.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems 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

According to the general rules, the project_id parameter should be optional to allow Spanner to automatically infer the project ID from Application Default Credentials (ADC) when not explicitly provided. We can update the type annotation to str | None and default it to None in the client initialization.

Suggested change
def run_full_text_search(project_id: str, instance_id: str, database_id: str) -> None:
"""Executes a parameterized full-text SEARCH() query ranked by SCORE().
Args:
project_id: The Google Cloud project ID.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems and
CatalogSearchIndex.
"""
client = spanner.Client(project=project_id)
database = client.instance(instance_id).database(database_id)
def run_full_text_search(
project_id: str | None, instance_id: str, database_id: str
) -> None:
"""Executes a parameterized full-text SEARCH() query ranked by SCORE().
Args:
project_id: The Google Cloud project ID. If None, it is inferred from ADC.
instance_id: The Enterprise-edition Spanner instance ID.
database_id: The Spanner database ID containing CatalogItems and
CatalogSearchIndex.
"""
client = spanner.Client(project=project_id)
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 +63 to +74
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: full-text 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

Since project_id can now be None (to support automatic project inference via ADC), we should use client.project in the error messages to ensure the resolved project ID is printed correctly.

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: full-text 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 '{client.project}' was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: full-text search failed on database '{database_id}' "
f"in instance '{instance_id}' for project '{client.project}': {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 +93 to +97
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

Update the --project-id command-line argument to default to os.environ.get("GOOGLE_CLOUD_PROJECT") (which evaluates to None if not set) instead of a hardcoded dummy string. This allows the Spanner client to automatically fall back to Application Default Credentials (ADC) to infer the project ID.

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

Set mock_client_class.return_value.project to PROJECT_ID to ensure that client.project returns the expected value during testing.

    mock_client_class.return_value.project = PROJECT_ID
    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 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 +77 to +81
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

Set mock_client_class.return_value.project to PROJECT_ID to ensure that client.project returns the expected value during testing.

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
mock_client_class.return_value.project = PROJECT_ID
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 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 +96 to +100
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

Set mock_client_class.return_value.project to PROJECT_ID to ensure that client.project returns the expected value during testing.

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
mock_client_class.return_value.project = PROJECT_ID
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 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