-1

I have a graph in which I need to execute similar queries repeatedly. I would like to be able to pass parameters to the function and have it return the results.

For instance, let's suppose I have a graph of movies and actors in which I want to find all the movies that an actor has acted in. I can write the following query:

MATCH (actor:Actor)-[:ACTED_IN]->(movie:Movie)
WHERE actor.name = 'Tom Hanks'
RETURN movie.title

Now, I want to reuse this query for different actors as well. Instead of repeating the same query, I want to write a function that takes an actor name as input and returns all the movies that the actor has acted in.

Abdul Manan
  • 117
  • 5

3 Answers3

1

The functionality that you want can be achieved using a query function that accepts parameters and will return the desired results. A parameterised query function can be created like this:

CREATE OR REPLACE FUNCTION getMoviesForActor(actorName STRING)
RETURNS LIST OF STRING
LANGUAGE cypher AS '
  MATCH (actor:Actor {name: $actorName})-[:ACTED_IN]->(movie:Movie)
  RETURN movie.title
';


CALL getMoviesForActor('Tom Hanks');

You can then call this function using different actor names to achieve the result you desire.

0

to answer the question back to the feature on docs continue reading you will discover that you can create your own customized function in another namespace.

CREATE OR REPLACE FUNCTION GetMovies(Actor_Name text)
RETURNS TABLE (movie_Title text)
AS $$
BEGIN
  RETURN QUERY
    SELECT movie.title FROM actor
    JOIN acted ON actor.actor_id = acted.actor_id
    JOIN movie ON acted.movie_id = movie.movie_id
    WHERE actor.name = Actor_Name;
END;
$$ LANGUAGE plpgsql;

notice this is Plpgsql as Cypher language is not directly supported by PostgreSQL if you want to use the Cypher language to implement your function then try to install plpython3u... then you can check the existence of the function using the

  SELECT 1 
  FROM pg_proc 
  WHERE proname = 'GetMovies' 
    AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'my_namespace')
);

it should return 1 then you can safely call your function to do the query again

SELECT * FROM GetMovies('Tom Hanks');
AmrShams07
  • 96
  • 1
  • 7
0

Apache AGE has support for user defined functions that you can use to avoid repetitive queries. You can use the following method getMoviesByActor to get movie title based to actor's name passed as an argument.

CREATE FUNCTION getMoviesByActor(actor_name text) RETURNS SETOF text AS $$
BEGIN
    RETURN QUERY
    MATCH (actor:Actor)-[:ACTED_IN]->(movie:Movie) WHERE actor.name = actor_name RETURN movie.title;
END;
$$ LANGUAGE plpgsql;

We can call this function in this way.

SELECT * FROM getMoviesByActor('Brad Pitt');
Abdul
  • 69
  • 5