Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Procedures & Functions in Neo4j

Introduction

Neo4j provides a powerful query language called Cypher which includes a variety of built-in functions and procedures. This lesson will cover the differences between functions and procedures, how to create and use them, and best practices for optimizing your Neo4j database operations.

Definitions

What are Procedures?

Procedures are operations that can be executed in Neo4j that perform specific tasks and can have side effects on the database, such as creating or modifying nodes and relationships.

What are Functions?

Functions, on the other hand, are operations that take input and return output without modifying the database state. They are typically used for calculations or data transformations.

Using Procedures

To use a procedure in Cypher, you typically call it with the `CALL` keyword.

Note: Procedures can be created in Java or other JVM languages and must be packaged as plugins.

CALL dbms.procedures() YIELD name
RETURN name;
        

Using Functions

Functions can be called directly in your Cypher queries. For example:


MATCH (n:Person)
RETURN n.name, size(n.friends) AS numberOfFriends;
        

Best Practices

  • Always validate input parameters for procedures to avoid errors.
  • Limit the use of side-effecting procedures in read-heavy workflows.
  • Use functions for calculations to keep queries efficient.
  • Document your procedures and functions for maintainability.

FAQ

What is the difference between a procedure and a function?

A procedure can modify the database and may have side effects, while a function is stateless and only returns a value.

How do I create a custom procedure?

To create a custom procedure, you need to implement it in Java, compile it, and package it as a JAR file to be placed in the plugins directory of Neo4j.

Can I execute multiple procedures in one query?

Yes, you can call multiple procedures in a single Cypher query using the `CALL` statement.

Flowchart of Procedure and Function Usage


graph TD;
    A[Start] --> B{Is it a side-effect?};
    B -->|Yes| C[Use Procedure];
    B -->|No| D[Use Function];
    C --> E[Execute Procedure];
    D --> F[Execute Function];
    E --> G[End];
    F --> G;