Search code examples
memgraphdb

Can I extend Memgraph with a custom function?


I see that Memgraph has a bunch of functions include, but how do I define my own function and use it inside Memgraph? My goal is to inject my custom function that that I can use expression.


Solution

  • Basically you nned to implement a custom query module with any number of functions, as an example you can take a look under MAGE documentation.

    You can use so called "Memgraph Magic Functions" for this. Magic functions are user-defined and operate similarly to read and write procedures. However, they are meant for different purposes and should not alter the graph in any way (creating, deleting, or updating objects).

    Below is an example of how to create and run a function, demonstrating a basic scenario of fetching arguments and returning values as a list:

    @mgp.function
    def func_example(context: mgp.FuncCtx,
                argument: mgp.Any,
                opt_argument: mgp.Nullable[mgp.Any] = None):
        return_arguments = [argument]
    
        if opt_argument is not None:
          return_arguments.append(opt_argument)
    
        # Note that we do not need to specify the result Record as long as it is a
        # Memgraph defined value type.
        return return_arguments