如果此示例类似于在CSV文件中保存这些地理位置的方式:
id,description,geog
1,"description1","(-122.850334,49.189992)"
然后,将第三个字段读取到geography
类型列将不起作用,因为这不是一个有效的geography
常量.这些都不起作用:
id,description,geog
1,"description1","(-122.850334 49.189992)"
1,"description1","-122.850334,49.189992"
1,"description1","-122.850334 49.189992"
这将:
id,description,geog
1,"description1","point(-122.850334 49.189992)"
您可以将列更改为text
,按原样导入,在point
前面加上逗号,
,用空格
替换逗号,
,然后用alter
将类型恢复为geography(point,4326)
.Demo at db<>fiddle:
create table my_table (id int, description text, geog geography(Point,4326));
--preparing a test file:
copy (select '1,"abc","(-122.850334,49.189992)"') to '/tmp/my_file.csv';
alter table my_table
alter column geog type text;
copy my_table from '/tmp/my_file.csv' csv delimiter ',' quote '"';
select *,pg_typeof(geog) from my_table;
id |
description |
geog |
pg_typeof |
1 |
abc |
(-122.850334,49.189992) |
text |
update my_table
set geog='point'||replace(geog,',',' ')
returning *,pg_typeof(geog);
id |
description |
geog |
pg_typeof |
1 |
abc |
point(-122.850334 49.189992) |
text |
alter table my_table
alter column geog type geography(point,4326)
using geog::geography(point,4326);
select *,pg_typeof(geog),st_astext(geog) from my_table;
id |
description |
geog |
pg_typeof |
st_astext |
1 |
abc |
0101000020E6100000522B4CDF6BB65EC0354069A851984840 |
geography |
POINT(-122.850334 49.189992) |
您还可以利用这些值是有效的point
类型常量这是PostgreSQL built-in point
type,不要与PostGIS geometry(point)
混淆.Postgr point
可以直接接受这些值,然后从该值到PostGIS geometry(point)
和从该值到geography(point)
的预定义转换:
truncate my_table;
copy (select '1,"abc","(-122.850334,49.189992)"') to '/tmp/my_file.csv';
alter table my_table
drop column if exists geog,
add column geog point;
copy my_table from '/tmp/my_file.csv' csv delimiter ',' quote '"';
alter table my_table
alter column geog type geography(point,4326)
using geog::geometry(point)::geography(point,4326);