Neo4j Graph Database Fundamentals · 课时

存储过程与 UDF

学习编写和部署自定义存储过程与用户定义函数,以封装复杂逻辑并扩展 Cypher

第 1 / 4 课11 个步骤

存储过程与 UDF 是 CoddyKit 上的免费 Neo4j Graph Database Fundamentals 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Neo4j Graph Database Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Neo4j Graph Database Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

免费开始

用 AI 导师学习 Neo4j Graph Database Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「存储过程与 UDF」课时是免费的吗?

是的 — 「存储过程与 UDF」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Neo4j Graph Database Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Neo4j Graph Database Fundamentals 课程共包含 4 节课。

「存储过程与 UDF」这节课中我会学到什么?

学习编写和部署自定义存储过程与用户定义函数,以封装复杂逻辑并扩展 Cypher 你通过在浏览器中直接运行的动手代码来练习 Neo4j Graph Database Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Neo4j Graph Database Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Neo4j Graph Database Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「存储过程与 UDF」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Neo4j Graph Database Fundamentals 课中编写并运行代码吗?

能。每节 Neo4j Graph Database Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 存储过程与 UDF
  2. 与 BI 和可视化工具集成
  3. 高级数据摄取管道
  4. Neo4j 中的全文搜索与向量搜索
← 返回 Neo4j Graph Database Fundamentals