Can I split a query in multiple queries or create parallelism to speed a query?

后端 未结 3 1637
春和景丽
春和景丽 2021-01-11 18:04

I have a table avl_pool, and I have a function to find on the map the link nearest to that (x, y) position.

The performance of this select

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 18:51

    Consider marking your map.get_near_link function as PARALLEL SAFE. This will tell the database engine that it is allowed to try generate a parallel plan when executing the function:

    PARALLEL UNSAFE indicates that the function can't be executed in parallel mode and the presence of such a function in an SQL statement forces a serial execution plan. This is the default. PARALLEL RESTRICTED indicates that the function can be executed in parallel mode, but the execution is restricted to parallel group leader. PARALLEL SAFE indicates that the function is safe to run in parallel mode without restriction.

    There are several settings which can cause the query planner not to generate a parallel query plan under any circumstances. Consider this documentation:

    • 15.4. Parallel Safety

    • 15.2. When Can Parallel Query Be Used?

    On my reading, you may be able to achieve a parallel plan if you refactor your function like this:

    CREATE OR REPLACE FUNCTION map.get_near_link(
        x NUMERIC,
        y NUMERIC,
        azim NUMERIC)
    RETURNS TABLE
    (Link_ID INTEGER, Distance INTEGER, Sendito TEXT, Geom GEOGRAPHY)
    AS
    $$
            SELECT 
                   S.Link_ID,
                   TRUNC(ST_Distance(ST_GeomFromText('POINT('|| X || ' ' || Y || ')',4326), S.geom) * 100000)::INTEGER AS distance,
                   S.sentido,
                   v.geom
            FROM (
              SELECT *
              FROM map.vzla_seg
              WHERE ABS(Azim - S.azimuth) NOT BETWEEN 30 AND 330
            ) S
              INNER JOIN map.vzla_rto v
                ON S.link_id = v.link_id
            WHERE
                ST_Distance(ST_GeomFromText('POINT('|| X || ' ' || Y || ')',4326), S.geom) * 100000 < 50
            ORDER BY
                S.geom <-> ST_GeomFromText('POINT('|| X || ' ' || Y || ')', 4326)
            LIMIT 1
    $$
    LANGUAGE SQL
    PARALLEL SAFE -- Include this parameter
    ;
    

    If the query optimiser will generate a parallel plan when executing this function, you won't need to implement your own parallelisation logic.

提交回复
热议问题