如何将整个 BigQuery table 导出到 GeoJSON

How to export entire BigQuery table to GeoJSON

我有一个 BigQuery table:

其中 geometry 列的类型为 GEOGRAPHY:

我想将此 table 导出为 GeoJSON 格式。我知道如何将 table 导出为简单的 JSON(参见 here),这不是我的目标。我也知道如何获取 geometry 列的各个行作为 GeoJSON:

问题是它适用于单个行,而不是整个列,也不是 table。

预期输出:

{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "description": "aaa" }, "geometry": { "type": "Point", "coordinates": [ 60.0, 10.0 ] } },
{ "type": "Feature", "properties": { "description": "bbb" }, "geometry": { "type": "Point", "coordinates": [ 65.0, 15.0 ] } }
]
}

如何从 BigQuery table 中获取此 GeoJSON 字符串或文件?

以下查询将生成您期望的输出。

WITH geodata AS (
  SELECT ST_GEOGPOINT(60., 10.) AS geometry, 'aaa' AS description
   UNION ALL
  SELECT ST_GEOGPOINT(65., 15.) AS geometry, 'bbb' AS description
),
ndjson AS (
  SELECT STRUCT(
           "Feature" AS type, 
           STRUCT(description) AS properties,
           STRUCT(
             "Point" AS type, 
             [ST_X(geometry),ST_Y(geometry)] AS coordinates
           ) AS geometry
         ) json
    FROM geodata
)
SELECT TO_JSON_STRING(STRUCT(
         "FeatureCollection" AS type,
         ARRAY_AGG(json) AS features
       )) 
  FROM ndjson;

输出:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "description": "aaa"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          59.99999999999999,
          10
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "description": "bbb"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          65,
          14.999999999999998
        ]
      }
    }
  ]
}

但是如果你有大量的GEO_POINTs,你最好将每个GEO_POINT导出为NDJSON(Newlined-Delimter JSON),而不是将所有行聚合成一个 JSON 字符串。

我通常做的是将 table 导出到 BQ 原生 new-line-delimited JSON,使用 ST_AsGeoJson 生成 GeoJson 格式的几何字段。然后很容易将其转换为 GeoJson 或 new-line-delimited GeoJson 使用此 node.js 脚本:

https://github.com/mentin/geoscripts/tree/master/bq2geojson