• Supported versions:

pgr_createTopology

pgr_createTopology — Construye una topología de red basada en la información de geometría.

Disponibilidad

  • Versión 2.0.0

    • Renombrado desde la versión 1.x

    • Función oficial

Descripción

La función devuelve:

  • OK después de que se ha construido la topología de red y la tabla de vértices.

  • FAIL cuando el la red topológica no se no se completó debido a un error.

Firmas

pgr_createTopology(edge_table, tolerance, [options])
options: [the_geom, id, source, target, rows_where, clean]
RETURNS VARCHAR

Parámetros

La función de creación de topología requiere los siguientes parámetros:

edge_table:

text La tabla de la red. (puede contener el nombre del esquema)

tolerancia:

float8 ajuste tolerancia de bordes desconectados. (en la unidad de proyección)

the_geom:

text nombre de la columna de la geometría en la tabla de la red. El valor por defecto es the_geom.

id:

text``Nombre de la columna de la clave principal de la tabla de red. Valor por defecto es ``id.

source:

id``Nombre de columna de origen de la tabla de red. El valor predeterminado es``source.

target:

text El nombre de la columna del nodo de llegada del segmento. El valor por defecto es target.

rows_where:

text Condición para SELECCIONAR un subconjunto de filas. El valor predeterminado es true para indicar todas las filas donde source o target tienen un valor nulo, de lo contrario se utiliza la condición.

limpio:

boolean Limpie cualquier topología previa. El valor predeterminado es false.

Advertencia

La edge_table se verán afectados

  • Los valores de la columna``source`` va a cambiar.

  • Cambian los valores de la columna``target``.

    • Un índice será creado, si no existe, para acelerar el proceso para las columnas siguientes:

      • id

      • the_geom

      • source

      • target

La función devuelve:

  • “” OK”” después de que se ha construido la topología de red.

    • Crea una tabla de vértices: <edge_table>_vertices_pgr.

    • Llena las columnas id y the_geom de la tabla de vértices.

    • Llena las columnas los origen y destino de la tabla de borde haciendo referencia al id de la tabla de los vértices.

  • FAIL cuando la topología de red no se construyó debido a un error:

    • Una columna de la tabla de red requerida no se encuentra o no es del tipo apropiado.

    • La condición no está bien formada.

    • Los nombres de origen, destino o id son las mismos.

    • No pudo determinarse el SRID de la geometría.

La tabla de vértices

La tabla de vértices es un requerimiento de las funciones pgr_analyzeGraph y pgr_analyzeOneWay.

La estructura de la tabla de los vértices es:

id:

bigint identificador del vértice.

cnt:

integer Número de vértices en la edge_table que referencian este vértice. Ver pgr_analyzeGraph.

chk:

integer Indicador de que el vértice podría tener un problema. Consulte pgr_analyzeGraph.

ein:

integer Número de vértices en edge_table que referencian a este vértice como (AS) entrante. Ver pgr_analyzeOneWay.

eout:

integer Número de vértices en edge_table que referencian este vértice como (AS) saliente. Ver pgr_analyzeOneWay.

the_geom:

geometry Valor de la geometría POINT del vértice.

Uso cuando las columnas de la tabla de borde coinciden con los valores por defecto:

La forma más sencilla de utilizar pgr_createTopology es:

SELECT  pgr_createTopology('edges', 0.001, 'geom');
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('edges', 0.001, 'geom', 'id', 'source', 'target', rows_where := 'true', clean := f)
NOTICE:  Performing checks, please wait .....
NOTICE:  Creating Topology, Please wait...
NOTICE:  -------------> TOPOLOGY CREATED FOR  18 edges
NOTICE:  Rows with NULL geometry or NULL id: 0
NOTICE:  Vertices table for table public.edges is: public.edges_vertices_pgr
NOTICE:  ----------------------------------------------
 pgr_createtopology
--------------------
 OK
(1 row)

Cuando los argumentos se escriben en el orden descrito en los parámetros:

Obtenemos el mismo resultado que la forma más sencilla de utilizar la función.

SELECT  pgr_createTopology('edges', 0.001,
    'geom', 'id', 'source', 'target');
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('edges', 0.001, 'geom', 'id', 'source', 'target', rows_where := 'true', clean := f)
NOTICE:  Performing checks, please wait .....
NOTICE:  Creating Topology, Please wait...
NOTICE:  -------------> TOPOLOGY CREATED FOR  18 edges
NOTICE:  Rows with NULL geometry or NULL id: 0
NOTICE:  Vertices table for table public.edges is: public.edges_vertices_pgr
NOTICE:  ----------------------------------------------
 pgr_createtopology
--------------------
 OK
(1 row)

Advertencia

An error would occur when the arguments are not given in the appropriate order: In this example, the column id of the table ege_table is passed to the function as the geometry column, and the geometry column the_geom is passed to the function as the id column.

SELECT  pgr_createTopology('edges', 0.001,
    'id', 'geom');
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('edges', 0.001, 'id', 'geom', 'source', 'target', rows_where := 'true', clean := f)
NOTICE:  Performing checks, please wait .....
NOTICE:  ----> PGR ERROR in pgr_createTopology: Wrong type of Column id:geom
HINT:    ----> Expected type of geom is integer,smallint or bigint but USER-DEFINED was found
NOTICE:  Unexpected error raise_exception
 pgr_createtopology
--------------------
 FAIL
(1 row)

Cuando se utiliza la notación por nombre

Los parámetros definidos con un valor predeterminado se pueden omitir, siempre que el valor coincida con el valor predeterminado y el orden de los parámetros no importaría.

SELECT  pgr_createTopology('edges', 0.001,
    the_geom:='geom', id:='id', source:='source', target:='target');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('edges', 0.001,
    source:='source', id:='id', target:='target', the_geom:='geom');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('edges', 0.001, 'geom', source:='source');
 pgr_createtopology
--------------------
 OK
(1 row)

Seleccionar filas utilizando el parámetro rows_where

La selección de filas basadas en el id.

SELECT  pgr_createTopology('edges', 0.001, 'geom', rows_where:='id < 10');
 pgr_createtopology
--------------------
 OK
(1 row)

Selección de las filas en las que la geometría está cerca de la geometría de la fila con id = 5.

SELECT  pgr_createTopology('edges', 0.001, 'geom',
    rows_where:='geom && (SELECT st_buffer(geom, 0.05) FROM edges WHERE id=5)');
 pgr_createtopology
--------------------
 OK
(1 row)

Seleccionar las filas donde la geometría está cerca de la geometría de la fila con``gid`` =100 de la tabla othertable.

CREATE TABLE otherTable AS  (SELECT 100 AS gid,  st_point(2.5, 2.5) AS other_geom);
SELECT 1
SELECT  pgr_createTopology('edges', 0.001, 'geom',
    rows_where:='geom && (SELECT st_buffer(other_geom, 1) FROM otherTable WHERE gid=100)');
 pgr_createtopology
--------------------
 OK
(1 row)

Uso cuando las columnas de la tabla de borde NO COINCIDEN con los valores por defecto:

Para la siguiente tabla

CREATE TABLE mytable AS (SELECT id AS gid,  geom AS mygeom, source AS src , target AS tgt FROM edges) ;
SELECT 18

Usando notación posicional:

Los argumentos deben darse en el orden descrito en los parámetros.

Tenga en cuenta que en este ejemplo se utiliza la bandera clean. Así que recrea toda la tabla de vértices.

SELECT  pgr_createTopology('mytable', 0.001, 'mygeom', 'gid', 'src', 'tgt', clean := TRUE);
 pgr_createtopology
--------------------
 OK
(1 row)

Advertencia

An error would occur when the arguments are not given in the appropiriate order: In this example, the column gid of the table mytable is passed to the function AS the geometry column, and the geometry column mygeom is passed to the function AS the id column.

SELECT  pgr_createTopology('mytable', 0.001, 'gid', 'mygeom', 'src', 'tgt');
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('mytable', 0.001, 'gid', 'mygeom', 'src', 'tgt', rows_where := 'true', clean := f)
NOTICE:  Performing checks, please wait .....
NOTICE:  ----> PGR ERROR in pgr_createTopology: Wrong type of Column id:mygeom
HINT:    ----> Expected type of mygeom is integer,smallint or bigint but USER-DEFINED was found
NOTICE:  Unexpected error raise_exception
 pgr_createtopology
--------------------
 FAIL
(1 row)

Cuando se utiliza la notación por nombre

En este escenario omitir un parámetro crearía un error porque los valores predeterminados para los nombres de columna no coinciden con los nombres de columna de la tabla. El orden de los parámetros no importa:

SELECT  pgr_createTopology('mytable', 0.001, the_geom:='mygeom', id:='gid', source:='src', target:='tgt');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('mytable', 0.001, source:='src', id:='gid', target:='tgt', the_geom:='mygeom');
 pgr_createtopology
--------------------
 OK
(1 row)

Seleccionar filas utilizando el parámetro rows_where

Basado en id:

SELECT  pgr_createTopology('mytable', 0.001, 'mygeom', 'gid', 'src', 'tgt', rows_where:='gid < 10');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('mytable', 0.001, source:='src', id:='gid', target:='tgt', the_geom:='mygeom', rows_where:='gid < 10');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('mytable', 0.001, 'mygeom', 'gid', 'src', 'tgt',
    rows_where:='mygeom && (SELECT st_buffer(mygeom, 1) FROM mytable WHERE gid=5)');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('mytable', 0.001, source:='src', id:='gid', target:='tgt', the_geom:='mygeom',
    rows_where:='mygeom && (SELECT st_buffer(mygeom, 1) FROM mytable WHERE gid=5)');
 pgr_createtopology
--------------------
 OK
(1 row)

Seleccionar las filas donde la geometría está cerca de la geometría de la fila con``gid`` =100 de la tabla othertable.

SELECT  pgr_createTopology('mytable', 0.001, 'mygeom', 'gid', 'src', 'tgt',
    rows_where:='mygeom && (SELECT st_buffer(other_geom, 1) FROM otherTable WHERE gid=100)');
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT  pgr_createTopology('mytable', 0.001, source:='src', id:='gid', target:='tgt', the_geom:='mygeom',
    rows_where:='mygeom && (SELECT st_buffer(other_geom, 1) FROM otherTable WHERE gid=100)');
 pgr_createtopology
--------------------
 OK
(1 row)

Ejemplos Adicionales

Creación de una topología de ruteo

An alternate method to create a routing topology use pgr_extractVertices – Propuesto

Asegurarse de que la base de datos no tiene vertices_table

DROP TABLE IF EXISTS vertices_table;
NOTICE:  table "vertices_table" does not exist, skipping
DROP TABLE

Limpieza de las columnas de la topología de ruteo que se creará

UPDATE edges
SET source = NULL, target = NULL,
x1 = NULL, y1 = NULL,
x2 = NULL, y2 = NULL;
UPDATE 18

Crear la tabla de vértices

  • When the LINESTRING has a SRID then use geom::geometry(POINT, <SRID>)

  • For big edge tables that are been prepared,

    • Create it as UNLOGGED and

    • After the table is created ALTER TABLE .. SET LOGGED

SELECT  * INTO vertices_table
FROM pgr_extractVertices('SELECT id, geom FROM edges ORDER BY id');
SELECT 17

Inspeccionar la tabla de vértices

SELECT *
FROM vertices_table;
 id | in_edges | out_edges |       x        |  y  |                    geom
----+----------+-----------+----------------+-----+--------------------------------------------
  1 |          | {6}       |              0 |   2 | 010100000000000000000000000000000000000040
  2 |          | {17}      |            0.5 | 3.5 | 0101000000000000000000E03F0000000000000C40
  3 | {6}      | {7}       |              1 |   2 | 0101000000000000000000F03F0000000000000040
  4 | {17}     |           | 1.999999999999 | 3.5 | 010100000068EEFFFFFFFFFF3F0000000000000C40
  5 |          | {1}       |              2 |   0 | 010100000000000000000000400000000000000000
  6 | {1}      | {2,4}     |              2 |   1 | 01010000000000000000000040000000000000F03F
  7 | {4,7}    | {8,10}    |              2 |   2 | 010100000000000000000000400000000000000040
  8 | {10}     | {12,14}   |              2 |   3 | 010100000000000000000000400000000000000840
  9 | {14}     |           |              2 |   4 | 010100000000000000000000400000000000001040
 10 | {2}      | {3,5}     |              3 |   1 | 01010000000000000000000840000000000000F03F
 11 | {5,8}    | {9,11}    |              3 |   2 | 010100000000000000000008400000000000000040
 12 | {11,12}  | {13}      |              3 |   3 | 010100000000000000000008400000000000000840
 13 |          | {18}      |            3.5 | 2.3 | 01010000000000000000000C406666666666660240
 14 | {18}     |           |            3.5 |   4 | 01010000000000000000000C400000000000001040
 15 | {3}      | {16}      |              4 |   1 | 01010000000000000000001040000000000000F03F
 16 | {9,16}   | {15}      |              4 |   2 | 010100000000000000000010400000000000000040
 17 | {13,15}  |           |              4 |   3 | 010100000000000000000010400000000000000840
(17 rows)

Creación de la topología de ruteo en la tabla de aristas

Actualizar de la información de source

WITH
out_going AS (
  SELECT id AS vid, unnest(out_edges) AS eid, x, y
  FROM vertices_table
)
UPDATE edges
SET source = vid, x1 = x, y1 = y
FROM out_going WHERE id = eid;
UPDATE 18

Actualización de la información de target

WITH
in_coming AS (
  SELECT id AS vid, unnest(in_edges) AS eid, x, y
  FROM vertices_table
)
UPDATE edges
SET target = vid, x2 = x, y2 = y
FROM in_coming WHERE id = eid;
UPDATE 18

Inspección de la topología de ruteo

SELECT id, source, target, x1, y1, x2, y2
FROM edges ORDER BY id;
 id | source | target | x1  | y1  |       x2       | y2
----+--------+--------+-----+-----+----------------+-----
  1 |      5 |      6 |   2 |   0 |              2 |   1
  2 |      6 |     10 |   2 |   1 |              3 |   1
  3 |     10 |     15 |   3 |   1 |              4 |   1
  4 |      6 |      7 |   2 |   1 |              2 |   2
  5 |     10 |     11 |   3 |   1 |              3 |   2
  6 |      1 |      3 |   0 |   2 |              1 |   2
  7 |      3 |      7 |   1 |   2 |              2 |   2
  8 |      7 |     11 |   2 |   2 |              3 |   2
  9 |     11 |     16 |   3 |   2 |              4 |   2
 10 |      7 |      8 |   2 |   2 |              2 |   3
 11 |     11 |     12 |   3 |   2 |              3 |   3
 12 |      8 |     12 |   2 |   3 |              3 |   3
 13 |     12 |     17 |   3 |   3 |              4 |   3
 14 |      8 |      9 |   2 |   3 |              2 |   4
 15 |     16 |     17 |   4 |   2 |              4 |   3
 16 |     15 |     16 |   4 |   1 |              4 |   2
 17 |      2 |      4 | 0.5 | 3.5 | 1.999999999999 | 3.5
 18 |     13 |     14 | 3.5 | 2.3 |            3.5 |   4
(18 rows)

_images/Fig1-originalData.png

Topología generada

Con salida completa

En este ejemplo se inicia una topología limpia, con 5 aristas y, a continuación, se incrementa al resto de los bordes.

SELECT pgr_createTopology('edges',  0.001, 'geom', rows_where:='id < 6', clean := true);
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('edges', 0.001, 'geom', 'id', 'source', 'target', rows_where := 'id < 6', clean := t)
NOTICE:  Performing checks, please wait .....
NOTICE:  Creating Topology, Please wait...
NOTICE:  -------------> TOPOLOGY CREATED FOR  5 edges
NOTICE:  Rows with NULL geometry or NULL id: 0
NOTICE:  Vertices table for table public.edges is: public.edges_vertices_pgr
NOTICE:  ----------------------------------------------
 pgr_createtopology
--------------------
 OK
(1 row)

SELECT pgr_createTopology('edges',  0.001, 'geom');
NOTICE:  PROCESSING:
NOTICE:  pgr_createTopology('edges', 0.001, 'geom', 'id', 'source', 'target', rows_where := 'true', clean := f)
NOTICE:  Performing checks, please wait .....
NOTICE:  Creating Topology, Please wait...
NOTICE:  -------------> TOPOLOGY CREATED FOR  13 edges
NOTICE:  Rows with NULL geometry or NULL id: 0
NOTICE:  Vertices table for table public.edges is: public.edges_vertices_pgr
NOTICE:  ----------------------------------------------
 pgr_createtopology
--------------------
 OK
(1 row)

En el ejemplo se utiliza la red Datos Muestra.

Ver también

Índices y tablas