Cypher commands can be run in PL/pgSQL functions without restriction.

Data Setup

  1. SELECT *
  2. FROM cypher('imdb', $$
  3. CREATE (toby:actor {name: 'Toby Maguire'}),
  4. (tom:actor {name: 'Tom Holland'}),
  5. (willam:actor {name: 'Willam Dafoe'}),
  6. (robert:actor {name: 'Robert Downey Jr'}),
  7. (spiderman:movie {title: 'Spiderman'}),
  8. (no_way_home:movie {title: 'Spiderman: No Way Home'}),
  9. (homecoming:movie {title: 'Spiderman: Homecoming'}),
  10. (ironman:movie {title: 'Ironman'}),
  11. (tropic_thunder:movie {title: 'Tropic Thunder'}),
  12. (toby)-[:acted_in {role: 'Peter Parker', alter_ego: 'Spiderman'}]->(spiderman),
  13. (willam)-[:acted_in {role: 'Norman Osborn', alter_ego: 'Green Goblin'}]->(spiderman),
  14. (toby)-[:acted_in {role: 'Toby Maguire'}]->(tropic_thunder),
  15. (robert)-[:acted_in {role: 'Kirk Lazarus'}]->(tropic_thunder),
  16. (robert)-[:acted_in {role: 'Tony Stark', alter_ego: 'Ironman'}]->(homecoming),
  17. (tom)-[:acted_in {role: 'Peter Parker', alter_ego: 'Spiderman'}]->(homecoming),
  18. (tom)-[:acted_in {role: 'Peter Parker', alter_ego: 'Spiderman'}]->(no_way_home),
  19. (toby)-[:acted_in {role: 'Peter Parker', alter_ego: 'Spiderman'}]->(no_way_home),
  20. (willam)-[:acted_in {role: 'Norman Osborn', alter_ego: 'Green Goblin'}]->(no_way_home)
  21. $$) AS (a agtype);

Function Creation

  1. CREATE OR REPLACE FUNCTION get_all_actor_names()
  2. RETURNS TABLE(actor agtype)
  3. LANGUAGE plpgsql
  4. AS $BODY$
  5. BEGIN
  6. LOAD 'age';
  7. SET search_path TO ag_catalog;
  8. RETURN QUERY
  9. SELECT *
  10. FROM ag_catalog.cypher('imdb', $$
  11. MATCH (v:actor)
  12. RETURN v.name
  13. $$) AS (a agtype);
  14. END
  15. $BODY$;

Query:

  1. SELECT * FROM get_all_actor_names();

Results

actor
“Toby Maguire”
“Tom Holland”
“Willam Dafoe”
“Robert Downey Jr”
4 row(s) returned
  1. Developer's Note:
  2. It's recommended that users use the LOAD 'age' command and set the search_path in the function declaration, to ensure the CREATE FUNCTION command works consistently.

Dynamic Cypher

  1. CREATE OR REPLACE FUNCTION get_actors_who_played_role(role agtype)
  2. RETURNS TABLE(actor agtype, movie agtype)
  3. LANGUAGE plpgsql
  4. AS $function$
  5. DECLARE sql VARCHAR;
  6. BEGIN
  7. load 'age';
  8. SET search_path TO ag_catalog;
  9. sql := format('
  10. SELECT *
  11. FROM cypher(''imdb'', $$
  12. MATCH (actor)-[:acted_in {role: %s}]->(movie:movie)
  13. RETURN actor.name, movie.title
  14. $$) AS (actor agtype, movie agtype);
  15. ', role);
  16. RETURN QUERY EXECUTE sql;
  17. END
  18. $function$;
  1. SELECT * FROM get_actors_who_played_role('"Peter Parker"');

Results

actor movie
“Toby Maguire” “Spiderman”
“Toby Maguire” “Spiderman: No Way Home”
“Tom Holland” “Spiderman: No Way Home”
“Tom Holland” “Spiderman: Homecoming”
4 row(s) returned