我正在尝试将
geojson
数据导出到 PostgreSQL 中的表中。我在 geojson
中有多个 directory
文件作为输入传递给 PostgreSQL 函数。我循环遍历该目录中的所有文件名,然后使用 pg_read_file
读取文件数据,然后尝试构建 geojson_data
对象,然后我可以使用该对象在表中插入值。
我写的
plpgsql
函数是:
CREATE OR REPLACE FUNCTION insert_geojson_data(directory text) RETURNS void AS $$
DECLARE
file_name text;
geojson_data json;
begin
-- Loop through GeoJSON files in the specified directory
FOR file_name IN
SELECT *
FROM pg_ls_dir(directory)
loop
-- Read GeoJSON data from file
IF file_name LIKE '%.geojson' then
RAISE NOTICE 'GeoJSON data: %', pg_read_file(directory || '/' || file_name);
EXECUTE 'SELECT jsonb_agg(features) FROM jsonb_array_elements_text(($1::jsonb)->>''features'')'
INTO geojson_data
USING pg_read_file(directory || '/' || file_name);
-- Insert data into the states table
INSERT INTO states (shapeId, name, geometry)
select
geojson_data->>'properties'->>'shapeId',
geojson_data->>'properties'->>'name',
ST_GeomFromGeoJSON(geojson_data->>'geometry');
RAISE NOTICE 'Data from % inserted successfully', file_name;
END IF;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
现在,当我使用目录路径执行该函数时:
SELECT public.insert_geojson_data('path/to/directory');
我已经放了一个
RAISE NOTICE 'GeoJSON data: %', pg_read_file(directory || '/' || file_name);
打印效果如下:
GeoJSON data: {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
},
"type": "Polygon",
"coordinates": [
[
[95.23729640200742, 26.679843368876448],
[95.2356467872695, 26.68178477135018],
[95.23566295528121, 26.68507127991569],
[95.2504579873463, 26.685907840974153],
[95.24362625324903, 26.687443945981386],
[95.24011046522583, 26.685192466259366],
[95.23729640200742, 26.679843368876448]
]
]
},
"properties": {
"shapeId": "fc13a047-aaac-4e9e-ba39-5544f0ffb21c",
"type": "State",
"iso_group": "IND",
"name": "Arunanchal Pradesh",
"admin_level": 3
}
}
]
}
但是之后我收到了错误
SQL Error [42883]: ERROR: function jsonb_array_elements_text(text) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgSQL function insert_geojson_data(text) line 15 at EXECUTE
问题似乎出在下面的代码中,我无法弄清楚,希望在这里得到一些帮助。谢谢!
EXECUTE 'SELECT jsonb_agg(features) FROM jsonb_array_elements_text(($1::jsonb)->>''features'')'
INTO geojson_data
USING pg_read_file(directory || '/' || file_name);
问题是您使用的
->>
运算符将属性值转换为 text
,这不是您想要的。请改用 ->
,它会返回 json(b)
类型的值。
顺便说一句,没有理由在函数中使用
EXECUTE
动态 SQL:
SELECT jsonb_agg(features) INTO geojson_data
FROM jsonb_array_elements_text((pg_read_file(directory || '/' || file_name)::jsonb)->'features');