我已经创建了这两个函数,我想知道是否有更好的方法将 json 数组转换为多边形,而无需安装 PostGIS 扩展。
原始类型:
((-34.888733,-57.956764),(-34.92303,-57.99367),(-34.953579,-57.95255))
多边形到json:
["-34.888733,-57.956764","-34.92303,-57.99367","-34.953579,-57.95255"]
json_到_多边形:
((-34.888733,-57.956764),(-34.92303,-57.99367),(-34.953579,-57.95255))
create or replace function json_to_polygon(p_poly json, out p_out polygon) returns polygon
parallel safe
returns null on null input
immutable
language plpgsql
as $$
begin
if(p_poly is null) then
return;
end if;
select
polygon(concat('((', string_agg(x, '),('), '))'))
from
json_array_elements_text(p_poly) x
into
p_out;
end;
$$;
create or replace function polygon_to_json(p_poly polygon) returns json
parallel safe
returns null on null input
immutable
language plpgsql
as $$
begin
if(p_poly is null) then
return null;
end if;
return to_json(string_to_array(replace(replace(p_poly::text, '((', ''), '))', ''), '),('));
end;
$$;
是的,有一个更好的方法:
小提琴
我使用 SQL 标准函数的语法变体(Postgres 14 中添加)。请参阅:
显然,由于两个函数都声明了
STRICT
(=RETURNS NULL ON NULL INPUT
),我们不需要检查空输入。简单函数可以是
LANGUAGE sql
,因此它们可以内联。请参阅:concat()
只是STABLE
,不是IMMUTABLE
,而是使用IMMUTABLE
连接运算符||
。这样声明函数IMMUTABLE
是正确的,并且不会妨碍函数内联。参见:第三个
replace()
应该比拉进来的要快string_to_array()
。最后,我将
json_to_polygon()
其完全反转polygon_to_json()
,这样应该会更快,并且更易于阅读和维护。尽管如此,PostGIS确实有一些功能可以帮助解决这个问题......