Skip to content

Commit 5abcfd2

Browse files
committed
feat(bigquery): add bigquery_create_search_index sample to create a search index on a table
Problem: The BigQuery documentation (https://cloud.google.com/bigquery/docs/search-index) needs a standalone, tested Python code sample demonstrating how to create a search index on a table (region tag `bigquery_create_search_index`). Solution: - Add `create_search_index(project_id: str, dataset_id: str, table_id: str) -> None` in `bigquery/search/bigquery_create_search_index.py` (Create a BigQuery search index on ALL COLUMNS or selected columns of a table using CREATE SEARCH INDEX.) - Add unit tests (`bigquery/search/bigquery_create_search_index_test.py`) covering both the success path and API error handling (`GoogleAPICallError`)
1 parent 186be98 commit 5abcfd2

5 files changed

Lines changed: 167 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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_create_search_index]
16+
import sys
17+
18+
from google.api_core import exceptions
19+
from google.cloud import bigquery
20+
21+
22+
def create_search_index(
23+
project_id: str,
24+
dataset_id: str,
25+
table_id: str,
26+
) -> None:
27+
"""Creates a full-text search index across all columns of a BigQuery table.
28+
29+
Args:
30+
project_id: Google Cloud project ID (for example, 'example-project').
31+
dataset_id: BigQuery dataset ID containing the target table
32+
(for example, 'example_dataset').
33+
table_id: BigQuery table ID to index (for example, 'example_table').
34+
"""
35+
client = bigquery.Client(project=project_id)
36+
# Use a fixed search index name on the caller-supplied table.
37+
index_name = "example_search_index"
38+
table_ref = f"{project_id}.{dataset_id}.{table_id}"
39+
# Indexing ALL COLUMNS enables full-text SEARCH queries across every STRING or JSON field.
40+
sql = f"""
41+
CREATE SEARCH INDEX `{index_name}`
42+
ON `{table_ref}`(ALL COLUMNS);
43+
"""
44+
45+
try:
46+
print(f"Creating search index {index_name} on table: {table_ref}")
47+
query_job = client.query(sql)
48+
query_job.result()
49+
except exceptions.AlreadyExists as err:
50+
print(
51+
f"error: search index '{index_name}' already exists on table "
52+
f"'{table_id}' in dataset '{dataset_id}' for project '{project_id}': {err.message}",
53+
file=sys.stderr,
54+
)
55+
return
56+
except exceptions.GoogleAPICallError as err:
57+
print(
58+
f"error: failed to create search index '{index_name}' on table "
59+
f"'{table_id}' in dataset '{dataset_id}' for project '{project_id}': {err.message}",
60+
file=sys.stderr,
61+
)
62+
return
63+
64+
print(f"Resource ID: {table_ref}")
65+
print(f"Index Name: {index_name}")
66+
print(f"Job ID: {query_job.job_id}")
67+
print(f"Statement Type: {query_job.statement_type}")
68+
69+
70+
# [END bigquery_create_search_index]
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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_create_search_index
21+
22+
23+
def test_create_search_index_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_job.statement_type = "SCRIPT"
31+
mock_row = mock.MagicMock()
32+
mock_job.result.return_value = [mock_row]
33+
mock_client.query.return_value = mock_job
34+
monkeypatch.setattr(
35+
bigquery_create_search_index.bigquery,
36+
"Client",
37+
lambda project=None: mock_client,
38+
)
39+
40+
bigquery_create_search_index.create_search_index(
41+
project_id="example-project",
42+
dataset_id="example_dataset",
43+
table_id="example_table",
44+
)
45+
46+
captured = capsys.readouterr()
47+
assert "Resource ID:" in captured.out
48+
assert "example-project" in captured.out
49+
assert mock_client.query.called
50+
51+
52+
def test_create_search_index_error(
53+
monkeypatch: pytest.MonkeyPatch,
54+
capsys: pytest.CaptureFixture[str],
55+
) -> None:
56+
mock_client = mock.MagicMock()
57+
mock_client.query.side_effect = exceptions.AlreadyExists("resource error")
58+
monkeypatch.setattr(
59+
bigquery_create_search_index.bigquery,
60+
"Client",
61+
lambda project=None: mock_client,
62+
)
63+
64+
bigquery_create_search_index.create_search_index(
65+
project_id="example-project",
66+
dataset_id="example_dataset",
67+
table_id="example_table",
68+
)
69+
70+
captured = capsys.readouterr()
71+
assert "error:" in captured.err
72+
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.47.0

0 commit comments

Comments
 (0)