插入 GeoJSON 数据

使用 GeoJSON 数据来流式插入到 GEOGRAPHY 列中。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Python 设置说明进行操作。如需了解详情,请参阅 BigQuery Python API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

import geojson
from google.cloud import bigquery

bigquery_client = bigquery.Client()

# This example uses a table containing a column named "geo" with the
# GEOGRAPHY data type.
table_id = "my-project.my_dataset.my_table"

# Use the python-geojson library to generate GeoJSON of a line from LAX to
# JFK airports. Alternatively, you may define GeoJSON data directly, but it
# must be converted to a string before loading it into BigQuery.
my_geography = geojson.LineString([(-118.4085, 33.9416), (-73.7781, 40.6413)])
rows = [
    # Convert GeoJSON data into a string.
    {"geo": geojson.dumps(my_geography)}
]

#  table already exists and has a column
# named "geo" with data type GEOGRAPHY.
errors = bigquery_client.insert_rows_json(table_id, rows)
if errors:
    raise RuntimeError(f"row insert failed: {errors}")
else:
    print(f"wrote 1 row to {table_id}")

Ruby

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Ruby 设置说明进行操作。如需了解详情,请参阅 BigQuery Ruby API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

require "google/cloud/bigquery"
require "rgeo"
require "rgeo/geo_json"

def insert_geojson dataset_id = "your_dataset_id", table_id = "your_table_id"
  bigquery = Google::Cloud::Bigquery.new
  dataset  = bigquery.dataset dataset_id
  table    = dataset.table table_id

  # Use the RGeo library to generate GeoJSON of a line from LAX to
  # JFK airports. Alternatively, you may define GeoJSON data directly, but it
  # must be converted to a string before loading it into BigQuery.
  factory = RGeo::Geographic.spherical_factory
  my_line = factory.line_string([factory.point(-118.4085, 33.9416), factory.point(-73.7781, 40.6413)])
  row_data = [
    # Convert GeoJSON data into a string.
    { geo: RGeo::GeoJSON.encode(my_line).to_json }
  ]

  # Table already exists and has a column named "geo" with data type GEOGRAPHY.
  response = table.insert row_data

  if response.success?
    puts "Inserted GeoJSON row successfully"
  else
    puts "GeoJSON row insert failed: #{response.error_rows.first&.errors}"
  end
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器