0Pricing
Neo4j Graph Database Fundamentals · Leçon

Procédures stockées et fonctions définies par l’utilisateur

Apprenez à écrire et déployer des procédures stockées et des fonctions définies par l’utilisateur afin d’encapsuler une logique complexe et d’étendre Cypher.

Procédures stockées et fonctions définies par l’utilisateur est une leçon Neo4j Graph Database Fundamentals gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Neo4j Graph Database Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Neo4j Graph Database Fundamentals comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Extending Neo4j's Capabilities

Welcome to extending Neo4j! Sometimes, Cypher isn't enough for complex logic or specific integrations. That's where custom code comes in.

Neo4j allows you to extend its functionality using Stored Procedures and User-Defined Functions (UDFs), typically written in Java.

  • Stored Procedures perform actions, like creating nodes or running complex algorithms.
  • User-Defined Functions (UDFs) return values, just like built-in Cypher functions.

They encapsulate complex logic, improve query readability, and boost performance for repetitive tasks.

Procedures vs. User-Defined Functions

It's crucial to understand the difference between procedures and UDFs:

  • Stored Procedures:
    - Called with CALL package.procedure()
    - Can perform side effects (create, update, delete data)
    - Return tabular results (rows and columns)
    - Can access the graph database directly
  • User-Defined Functions (UDFs):
    - Called within Cypher expressions (e.g., RETURN my.udf(n.property))
    - Must be pure functions (no side effects)
    - Return a single scalar value (e.g., string, number, boolean, list)
    - Cannot modify the graph or access it directly

Stored Procedure Anatomy (Java)

Stored procedures are Java classes compiled into a JAR file. They use specific Neo4j annotations.

Here's the basic structure for a simple procedure that doesn't take any parameters and returns a string:

package com.coddykit;

import org.neo4j.procedure.Procedure;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.Description;
import org.neo4j.graphdb.Result;
import java.util.stream.Stream;

public class MyProcedures {

    // Define the output record structure
    public static class StringOutput {
        public String value;

        public StringOutput(String value) {
            this.value = value;
        }
    }

    @Procedure(value = "my.hello")
    @Description("Returns a simple greeting.")
    public Stream<StringOutput> hello() {
        return Stream.of(new StringOutput("Hello from CoddyKit!"));
    }
}

Key Elements of a Procedure

Let's break down the previous code:

  • @Procedure(value = "my.hello"): This annotation declares a method as a stored procedure and defines its full name (my.hello).
  • @Description: Provides a description visible in Neo4j Browser.
  • Output Class (StringOutput): Procedures return a Stream of custom objects. Each object represents a row in the result, and its public fields become the column names.
  • Stream<StringOutput>: The return type for procedures.

This Java code is ready to be compiled into a JAR and deployed.

Deploying Your Custom Procedure

To make your Java procedure available in Neo4j, you need to compile it and place the resulting JAR file into the database's plugins directory.

Steps:

  1. Compile your Java code into a JAR file (e.g., my-procedures.jar).
  2. Copy the JAR file into your Neo4j installation's plugins folder.
  3. Restart your Neo4j database instance.

After restarting, Neo4j will discover and register your new procedures and functions.

Calling a Stored Procedure

Once deployed, you can call your procedure using the CALL keyword in Cypher. Let's try calling our my.hello procedure:

CALL my.hello();

User-Defined Function (UDF) Anatomy

UDFs are similar to procedures but have different annotations and return types. They are designed to be used inline within Cypher expressions.

Here's the basic structure for a UDF that takes a string and returns a modified string:

package com.coddykit;

import org.neo4j.procedure.UserFunction;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.Description;

public class MyFunctions {

    @UserFunction("my.capitalize")
    @Description("Capitalizes the first letter of an input string.")
    public String capitalize(@Name("input") String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return Character.toUpperCase(input.charAt(0)) + input.substring(1);
    }
}

Key Elements of a UDF

Let's look at the UDF's components:

  • @UserFunction("my.capitalize"): This annotation declares a method as a UDF and defines its full name (my.capitalize).
  • @Name("input"): Specifies the name for the parameter when used in Cypher.
  • Return Type: UDFs return a single scalar value (e.g., String, Long, Boolean, List<String>). They do not return a Stream or custom output objects.

Like procedures, this Java code must be compiled into a JAR and deployed to the plugins folder.

Calling a User-Defined Function

After deploying your UDF, you can use it directly within Cypher queries as part of an expression. It behaves just like built-in functions.

Let's use our my.capitalize UDF:

RETURN my.capitalize("hello world");

// Or with graph data:
MATCH (p:Person)
RETURN p.name, my.capitalize(p.name) AS CapitalizedName;

Quick Check: Procedures & UDFs

Which of the following statements is TRUE regarding Neo4j Stored Procedures and User-Defined Functions (UDFs)?

Recap & Next Steps

You've learned how to extend Neo4j with custom Java code!

  • Stored Procedures execute complex actions, return tabular results, and are called with CALL.
  • User-Defined Functions (UDFs) return single scalar values, are pure functions (no side effects), and are used inline in Cypher expressions.
  • Both require Java code, specific Neo4j annotations, compilation into a JAR, and deployment to the Neo4j plugins directory.

These powerful extensions allow you to integrate custom logic, algorithms, and external services directly into your Neo4j environment, significantly expanding its capabilities.

Questions Fréquemment Posées

La leçon « Procédures stockées et fonctions définies par l’utilisateur » est-elle gratuite ?

Oui — le texte complet de « Procédures stockées et fonctions définies par l’utilisateur » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Neo4j Graph Database Fundamentals, passe à CoddyKit PRO. Le cours Neo4j Graph Database Fundamentals comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Procédures stockées et fonctions définies par l’utilisateur » ?

Apprenez à écrire et déployer des procédures stockées et des fonctions définies par l’utilisateur afin d’encapsuler une logique complexe et d’étendre Cypher. Tu pratiques Neo4j Graph Database Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Neo4j Graph Database Fundamentals ?

Aucune expérience préalable n'est requise. Neo4j Graph Database Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Procédures stockées et fonctions définies par l’utilisateur » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Neo4j Graph Database Fundamentals ?

Oui. Chaque leçon Neo4j Graph Database Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Procédures stockées et fonctions définies par l’utilisateur
  2. Intégrer des outils de BI et de visualisation
  3. Pipelines avancés d’ingestion de données
  4. Recherche en texte intégral et vectorielle dans Neo4j
← Retour à Neo4j Graph Database Fundamentals