Skip to content

Commit 13bed0c

Browse files
committed
feat(bigquery): add bigquery_search_table sample to search all columns of a table with SEARCH
Problem: The BigQuery documentation (https://cloud.google.com/bigquery/docs/search) needs a standalone, tested Python code sample demonstrating how to search all columns of a table with SEARCH (region tag `bigquery_search_table`). Solution: - Add `search_table(project_id: str) -> None` in `bigquery/search/bigquery_search_table.py` (Run a full-text search across all indexed or unindexed columns of a BigQuery table using the SEARCH function.) - Add unit tests (`bigquery/search/bigquery_search_table_test.py`) covering both the success path and API error handling (`GoogleAPICallError`)
1 parent 186be98 commit 13bed0c

5 files changed

Lines changed: 171 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START bigquery_search_table]
16+
import sys
17+
18+
from google.api_core import exceptions
19+
from google.cloud import bigquery
20+
21+
22+
def search_table(
23+
project_id: str,
24+
) -> None:
25+
"""Performs a full-text search across all columns of a BigQuery table using SEARCH.
26+
27+
Args:
28+
project_id: Google Cloud project ID used to bill the query job
29+
(for example, 'example-project').
30+
"""
31+
client = bigquery.Client(project=project_id)
32+
table_ref = "bigquery-public-data.thelook_ecommerce.users"
33+
# Pass the multi-token address query via ScalarQueryParameter and order by id for determinism.
34+
search_query = "Nelson Apt"
35+
job_config = bigquery.QueryJobConfig(
36+
query_parameters=[
37+
bigquery.ScalarQueryParameter("search_query", "STRING", search_query),
38+
]
39+
)
40+
sql = f"""
41+
SELECT
42+
u.id,
43+
u.first_name,
44+
u.last_name,
45+
u.street_address
46+
FROM `{table_ref}` AS u
47+
WHERE SEARCH(u, @search_query)
48+
ORDER BY u.id ASC
49+
LIMIT 10;
50+
"""
51+
52+
try:
53+
print(f"Searching table {table_ref} for term: {search_query}")
54+
query_job = client.query(sql, job_config=job_config)
55+
rows = list(query_job.result())
56+
except exceptions.NotFound as err:
57+
print(
58+
f"error: table '{table_ref}' not found when querying from project "
59+
f"'{project_id}': {err.message}",
60+
file=sys.stderr,
61+
)
62+
return
63+
except exceptions.GoogleAPICallError as err:
64+
print(
65+
f"error: failed to search table '{table_ref}' in project "
66+
f"'{project_id}': {err.message}",
67+
file=sys.stderr,
68+
)
69+
return
70+
71+
print(f"Resource ID: {table_ref}")
72+
print(f"Job ID: {query_job.job_id}")
73+
print(f"Matching Rows: {len(rows)}")
74+
print(f"Search Term: {search_query}")
75+
76+
77+
# [END bigquery_search_table]
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from unittest import mock
16+
17+
from google.api_core import exceptions
18+
import pytest
19+
20+
import bigquery_search_table
21+
22+
23+
def test_search_table_success(
24+
monkeypatch: pytest.MonkeyPatch,
25+
capsys: pytest.CaptureFixture[str],
26+
) -> None:
27+
mock_client = mock.MagicMock()
28+
mock_job = mock.MagicMock()
29+
mock_job.job_id = "example-job-123"
30+
mock_row = mock.MagicMock()
31+
mock_row.id = 101
32+
mock_job.result.return_value = [mock_row]
33+
mock_client.query.return_value = mock_job
34+
monkeypatch.setattr(
35+
bigquery_search_table.bigquery,
36+
"Client",
37+
lambda project=None: mock_client,
38+
)
39+
40+
bigquery_search_table.search_table(
41+
project_id="example-project",
42+
)
43+
44+
captured = capsys.readouterr()
45+
assert "Resource ID: bigquery-public-data.thelook_ecommerce.users" in captured.out
46+
assert "Matching Rows: 1" in captured.out
47+
assert "Search Term: Nelson Apt" in captured.out
48+
assert mock_client.query.called
49+
50+
51+
def test_search_table_error(
52+
monkeypatch: pytest.MonkeyPatch,
53+
capsys: pytest.CaptureFixture[str],
54+
) -> None:
55+
mock_client = mock.MagicMock()
56+
mock_client.query.side_effect = exceptions.NotFound("resource error")
57+
monkeypatch.setattr(
58+
bigquery_search_table.bigquery,
59+
"Client",
60+
lambda project=None: mock_client,
61+
)
62+
63+
bigquery_search_table.search_table(
64+
project_id="example-project",
65+
)
66+
67+
captured = capsys.readouterr()
68+
assert "error:" in captured.err
69+
assert "example-project" in captured.err

‎bigquery/search/noxfile_config.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
TEST_CONFIG_OVERRIDE = {
16+
# You can opt out from the test for specific Python versions.
17+
"ignored_versions": ["2.7", "3.7", "3.8", "3.9", "3.10", "3.11"],
18+
# Enforce type hints on new samples.
19+
"enforce_type_hints": True,
20+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
21+
"pip_version_override": None,
22+
"envs": {},
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytest==9.0.3; python_version >= "3.10"

‎bigquery/search/requirements.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
google-cloud-bigquery==3.35.1

0 commit comments

Comments
 (0)