Todos os produtos
Search
Central de documentação

ApsaraDB RDS:ST_makeTrajectory

Última atualização: Sep 02, 2026

Constrói um objeto de trajetória.

Sintaxe

  • Sintaxe 1

    trajectory ST_makeTrajectory(leaftype type, geometry spatial, tsrange timespan, cstring attrs_json);
  • Sintaxe 2

    trajectory ST_makeTrajectory(leaftype type, geometry spatial, timestamp start, timestamp end, cstring attrs_json);
  • Sintaxe 3

    trajectory ST_makeTrajectory(leaftype type, geometry spatial, timestamp[] timeline, cstring attrs_json);
  • Sintaxe 4

    trajectory ST_makeTrajectory(leaftype type, float8[] x, float8[] y, integer srid, timestamp[] timeline, text[] attr_field_names, int4[] attr_int4, float8[] attr_float8, text[] attr_cstring, anyarray attr_any);
  • Sintaxe 5

    trajectory ST_makeTrajectory(anyarray rows, bool hasz, cstring[] attrnames);

Parâmetros

Parâmetro

Descrição

type

Tipo da trajetória. Atualmente, há suporte apenas para ST_POINT.

spatial

Objeto espacial da trajetória baseado no tipo LineString ou Point.

timespan

Um tsrange que contém os horários inicial e final.

start

Horário inicial da trajetória.

end

Horário final da trajetória.

timeline

Linha do tempo da trajetória. A quantidade de pontos temporais deve corresponder ao número de pontos no LineString.

attrs_json

Atributos e eventos da trajetória em formato JSON. Este parâmetro pode ser definido como null.

attr_field_names

Nomes de todos os campos que representam os atributos da trajetória (array).

x

Coordenadas x usadas para construir o objeto geométrico (array).

y

Coordenadas y usadas para construir o objeto geométrico (array).

srid

Identificador de referência espacial obrigatório.

rows

Tabela usada para representar a trajetória. A primeira coluna deve ser do tipo TimeStamp; a segunda e a terceira devem ser do tipo float8.

hasz

Indica se a trajetória é tridimensional.

  • true: trajetória 3D. A quarta coluna deve ser do tipo float8.

  • false: trajetória 2D. A quarta coluna representa os atributos da trajetória.

attrnames

Nomes dos atributos na trajetória. Se você não especificar esse parâmetro, o valor padrão será attr1, attr2....

  1. O formato de attrs_json é o seguinte:

    {
      "leafcount": 3,
      "attributes": {
        "velocity": {
          "type": "integer",
          "length": 2,
          "nullable": true,
          "value": [
            120,
            null,
            140
          ]
        },
        "accuracy": {
          "type": "float",
          "length": 4,
          "nullable": false,
          "value": [
            120,
            130,
            140
          ]
        },
        "bearing": {
          "type": "float",
          "length": 8,
          "nullable": false,
          "value": [
            120,
            130,
            140
          ]
        },
        "vesname": {
          "type": "string",
          "length": 20,
          "nullable": true,
          "value": [
            "dsff",
            "fgsd",
            null
          ]
        },
        "active": {
          "type": "timestamp",
          "nullable": false,
          "value": [
            "Fri Jan 01 14:30:00 2010",
            "Fri Jan 01 15:00:00 2010",
            "Fri Jan 01 15:30:00 2010"
          ]
        }
      },
      "events": [
        {
          "1": "Fri Jan 01 14:30:00 2010"
        },
        {
          "2": "Fri Jan 01 15:00:00 2010"
        },
        {
          "3": "Fri Jan 01 15:30:00 2010"
        }
      ]
    }

    leafcount Quantidade de pontos contidos na trajetória. Esse valor deve corresponder ao número de pontos espaciais no objeto espacial e também representa a quantidade de valores em cada campo de atributo. Todos os campos de atributo devem conter o mesmo número de elementos.

    attributes Itens de atributo que incluem as definições de campo e as sequências de valores de todos os atributos. Este parâmetro deve existir simultaneamente com leafcount. Definições e requisitos dos atributos:

    • O nome de um atributo pode ter até 60 caracteres.

    • type: tipo do campo. Há suporte para cinco tipos de dados: integer, float, string, timestamp e bool.

    • length: comprimento do campo:

      • integer aceita comprimentos de 1, 2, 4 ou 8.

      • float aceita comprimentos de 4 ou 8.

      • string permite comprimento personalizado. Se o comprimento não for especificado, o valor padrão será 64, com limite máximo de 253. O valor de length corresponde ao número real de caracteres, sem incluir o identificador de término.

      • O comprimento de timestamp é opcional, com valor padrão de 8.

      • O comprimento de bool é opcional, com valor padrão de 1.

    • nullable: define se o campo aceita valores nulos. O valor true permite nulos; false não permite. O padrão é true.

    • value: sequência de valores do campo, expressa como um array JSON. Um elemento nulo é representado por null.

    events Eventos da trajetória. Múltiplos eventos são expressos como um array JSON. Cada elemento do array é representado por um par "chave:valor" em JSON, em que a chave indica o tipo de evento e o valor corresponde ao horário do evento.

  2. Se o parâmetro de tempo fornecido for timespan ou start e end, os pontos temporais serão interpolados com base na quantidade de pontos em spatial.

  3. Agrupe as linhas de uma tabela e converta-as em uma trajetória usando a função array_agg(row(table.*)). Para mais informações, consulte a Sintaxe 5.

  4. Caso nenhuma das sintaxes anteriores atenda às suas necessidades, personalize a função MakeTrajectory. Os seis primeiros parâmetros são fixos; os subsequentes podem ser personalizados conforme os requisitos do seu negócio:

    CREATE OR REPLACE FUNCTION  _ST_MakeTrajectory(type leaftype, x float8[], y float8[] , srid integer, timespan timestamp[],
        attrs_name cstring[], attr1 float8[], attr2 float4[], attr3 timestamp[])
        RETURNS trajectory
        AS '$libdir/libpg-trajectory-x.y','sqltr_traj_make_all_array'
        LANGUAGE 'c' IMMUTABLE Parallel SAFE;
    Nota

    No exemplo, x.y representa a versão do GanosBase, verificável ao executar ST_Version. Por exemplo, para a versão 4.5, o valor é libpg-trajectory-4.5.

    Se ocorrer um erro de permissão ao criar uma função personalizada, envie um ticket.

Exemplos

-- (1) ST_MakeTrajectory with timestamp range
select ST_MakeTrajectory('STPOINT'::leaftype, st_geomfromtext('LINESTRING (114 35, 115 36, 116 37)', 4326), '[2010-01-01 14:30, 2010-01-01 15:30)'::tsrange, '{"leafcount":3,"attributes":{"velocity": {"type": "integer", "length": 2,"nullable" : true,"value": [120, 130, 140]}, "accuracy": {"type": "float", "length": 4, "nullable" : false,"value": [120, 130, 140]}, "bearing": {"type": "float", "length": 8, "nullable" : false,"value": [120, 130, 140]}, "vesname": {"type": "string", "length": 20, "nullable" : true,"value": ["adsf", "sdf", "sdfff"]}, "active": {"type": "timestamp", "nullable" : false,"value": ["Fri Jan 01 14:30:00 2010", "Fri Jan 01 15:00:00 2010", "Fri Jan 01 15:30:00 2010"]}}, "events": [{"1" : "Fri Jan 01 14:30:00 2010"}, {"2" : "Fri Jan 01 15:00:00 2010"}, {"3" : "Fri Jan 01 15:30:00 2010"}]}');                        st_maketrajectory         
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 {"trajectory":{"version":1,"type":"STPOINT","leafcount":3,"start_time":"2010-01-01 14:30:00","end_time":"2010-01-01 15:30:00","spatial":"SRID=4326;LINESTRING(114 35,115 36,116 37)","timeline":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"],"attributes":{"leafcount":3,"velocity":{"type":"integer","length":2,"nullable":true,"value":[120,130,140]},"accuracy":{"type":"float","length":4,"nullable":false,"value":[120.0,130.0,140.0]},"bearing":{"type":"float","length":8,"nullable":false,"value":[120.0,130.0,140.0]},"vesname":{"type":"string","length":20,"nullable":true,"value":["adsf","sdf","sdfff"]},"active":{"type":"timestamp","length":8,"nullable":false,"value":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"]}},"events":[{"1":"2010-01-01 14:30:00"},{"2":"2010-01-01 15:00:00"},{"3":"2010-01-01 15:30:00"}]}}
(1 row)

-- (2) ST_MakeTrajectory with start timestamp and end timestamp
select ST_MakeTrajectory('STPOINT'::leaftype, st_geomfromtext('LINESTRING (114 35, 115 36, 116 37)', 4326), '2010-01-01 14:30'::timestamp, '2010-01-01 15:30'::timestamp, '{"leafcount":3,"attributes":{"velocity": {"type": "integer", "length": 2,"nullable" : true,"value": [120, 130, 140]}, "accuracy": {"type": "float", "length": 4, "nullable" : false,"value": [120, 130, 140]}, "bearing": {"type": "float", "length": 8, "nullable" : false,"value": [120, 130, 140]}, "vesname": {"type": "string", "length": 20, "nullable" : true,"value": ["adsf", "sdf", "sdfff"]}, "active": {"type": "timestamp", "nullable" : false,"value": ["Fri Jan 01 14:30:00 2010", "Fri Jan 01 15:00:00 2010", "Fri Jan 01 15:30:00 2010"]}}, "events": [{"1" : "Fri Jan 01 14:30:00 2010"}, {"2" : "Fri Jan 01 15:00:00 2010"}, {"3" : "Fri Jan 01 15:30:00 2010"}]}');                        st_maketrajectory         
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 {"trajectory":{"version":1,"type":"STPOINT","leafcount":3,"start_time":"2010-01-01 14:30:00","end_time":"2010-01-01 15:30:00","spatial":"SRID=4326;LINESTRING(114 35,115 36,116 37)","timeline":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"],"attributes":{"leafcount":3,"velocity":{"type":"integer","length":2,"nullable":true,"value":[120,130,140]},"accuracy":{"type":"float","length":4,"nullable":false,"value":[120.0,130.0,140.0]},"bearing":{"type":"float","length":8,"nullable":false,"value":[120.0,130.0,140.0]},"vesname":{"type":"string","length":20,"nullable":true,"value":["adsf","sdf","sdfff"]},"active":{"type":"timestamp","length":8,"nullable":false,"value":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"]}},"events":[{"1":"2010-01-01 14:30:00"},{"2":"2010-01-01 15:00:00"},{"3":"2010-01-01 15:30:00"}]}}
(1 row)

-- (3) ST_MakeTrajectory with timestamp array
select ST_MakeTrajectory('STPOINT'::leaftype, st_geomfromtext('LINESTRING (114 35, 115 36, 116 37)', 4326), ARRAY['2010-01-01 14:30'::timestamp, '2010-01-01 15:00'::timestamp, '2010-01-01 15:30'::timestamp], '{"leafcount":3,"attributes":{"velocity": {"type": "integer", "length": 2,"nullable" : true,"value": [120, 130, 140]}, "accuracy": {"type": "float", "length": 4, "nullable" : false,"value": [120, 130, 140]}, "bearing": {"type": "float", "length": 8, "nullable" : false,"value": [120, 130, 140]}, "vesname": {"type": "string", "length": 20, "nullable" : true,"value": ["adsf", "sdf", "sdfff"]}, "active": {"type": "timestamp", "nullable" : false,"value": ["Fri Jan 01 14:30:00 2010", "Fri Jan 01 15:00:00 2010", "Fri Jan 01 15:30:00 2010"]}}, "events": [{"1" : "Fri Jan 01 14:30:00 2010"}, {"2" : "Fri Jan 01 15:00:00 2010"}, {"3" : "Fri Jan 01 15:30:00 2010"}]}');                        st_maketrajectory         
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 {"trajectory":{"version":1,"type":"STPOINT","leafcount":3,"start_time":"2010-01-01 14:30:00","end_time":"2010-01-01 15:30:00","spatial":"SRID=4326;LINESTRING(114 35,115 36,116 37)","timeline":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"],"attributes":{"leafcount":3,"velocity":{"type":"integer","length":2,"nullable":true,"value":[120,130,140]},"accuracy":{"type":"float","length":4,"nullable":false,"value":[120.0,130.0,140.0]},"bearing":{"type":"float","length":8,"nullable":false,"value":[120.0,130.0,140.0]},"vesname":{"type":"string","length":20,"nullable":true,"value":["adsf","sdf","sdfff"]},"active":{"type":"timestamp","length":8,"nullable":false,"value":["2010-01-01 14:30:00","2010-01-01 15:00:00","2010-01-01 15:30:00"]}},"events":[{"1":"2010-01-01 14:30:00"},{"2":"2010-01-01 15:00:00"},{"3":"2010-01-01 15:30:00"}]}}
(1 row)  

-- (4) json is null
select ST_MakeTrajectory('STPOINT'::leaftype, st_geomfromtext('LINESTRING (114 35, 115 36, 116 37)', 4326), '[2010-01-01 14:30, 2010-01-01 15:30)'::tsrange, null); 
                        st_maketrajectory                                                                                                                  
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 
{"trajectory":{"leafsize":3,"starttime":"Fri Jan 01 14:30:00 2010","endtime":"Fri Jan 01 15:30:00 2010","spatial":"LINESTRING(114 35,115 36,116 37)","timeline":["Fri Jan 01 14:30:00 2010","Fri Jan 01 15:00:00 2010","Fri Jan 01 15:30:00 2010"]}}
(1 row)

-- (5) ST_MakeTrajectory make from points
select st_makeTrajectory('STPOINT'::leaftype, ARRAY[1::float8], ARRAY[2::float8], 4326, ARRAY['2010-01-01 11:30'::timestamp], ARRAY['velocity'], ARRAY[1::int4], NULL, NULL, NULL::anyarray);
                                                            st_maketrajectory                             

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{"trajectory":{"version":1,"type":"STPOINT","leafcount":1,"start_time":"2010-01-01 11:30:00","end_time":"2010-01-01 11:30:00","spatial":"SRID=4326;POINT(1 2)","timeline":["2010-01-01 11:30:00"],"attributes":{"leafcount":1,"velocity":{"type":"integer","length":4,"nullable":true,"value":[1]}}}}
(1 row)

-- (6) ST_MakeTrajectory from table
CREATE TABLE tjrows(t timestamp, x double precision, y double precision, id int, attr text);

INSERT into tjrows values ('2000-01-01 10:00:00', 3, 5, 1, 'the first point'), ('2000-01-01 11:00:00', 4, 6,2, 'the second point'), ('2000-01-01 11:05:00', 5,7,3,'the third point');

select ST_MakeTrajectory(array_agg(row(tjrows.*)), false, '{"id","attr"}'::cstring[]) from tjrows;

                       st_maketrajectory

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------
 {"trajectory":{"version":1,"type":"STPOINT","leafcount":3,"start_time":"2000-01-01 10:00:00","end_time":"2000-01-01 11:05:00","spatial":"LINESTRING(3 5,4 6,5 7)","timeline":["2000-01-01 10:00:00",
"2000-01-01 11:00:00","2000-01-01 11:05:00"],"attributes":{"leafcount":3,"id":{"type":"integer","length":4,"nullable":true,"value":[1,2,3]},"attr":{"type":"string","length":64,"nullable":true,"valu
e":["the first point","the second point","the third point"]}}}}
(1 row)