|
| 1 | +# Copyright 2020 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 | +# http://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 | + |
| 16 | +def insert_geojson(override_values={}): |
| 17 | + # [START bigquery_insert_geojson] |
| 18 | + import geojson |
| 19 | + from google.cloud import bigquery |
| 20 | + |
| 21 | + bigquery_client = bigquery.Client() |
| 22 | + |
| 23 | + # This example uses a table containing a column named "geo" with the |
| 24 | + # GEOGRAPHY data type. |
| 25 | + table_id = "my-project.my_dataset.my_table" |
| 26 | + # [END bigquery_insert_geojson] |
| 27 | + # To facilitate testing, we replace values with alternatives |
| 28 | + # provided by the testing harness. |
| 29 | + table_id = override_values.get("table_id", table_id) |
| 30 | + # [START bigquery_insert_geojson] |
| 31 | + |
| 32 | + # Use the python-geojson library to generate GeoJSON of a line from LAX to |
| 33 | + # JFK airports. Alternatively, you may define GeoJSON data directly, but it |
| 34 | + # must be converted to a string before loading it into BigQuery. |
| 35 | + my_geography = geojson.LineString([(-118.4085, 33.9416), (-73.7781, 40.6413)]) |
| 36 | + rows = [ |
| 37 | + # Convert GeoJSON data into a string. |
| 38 | + {"geo": geojson.dumps(my_geography)} |
| 39 | + ] |
| 40 | + |
| 41 | + # table already exists and has a column |
| 42 | + # named "geo" with data type GEOGRAPHY. |
| 43 | + errors = bigquery_client.insert_rows_json(table_id, rows) |
| 44 | + if errors: |
| 45 | + raise RuntimeError(f"row insert failed: {errors}") |
| 46 | + else: |
| 47 | + print(f"wrote 1 row to {table_id}") |
| 48 | + # [END bigquery_insert_geojson] |
| 49 | + return errors |
0 commit comments