You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为Memgraph扩展自定义函数?自定义函数定义与使用方法

在Memgraph中定义和使用自定义函数

Memgraph支持两种核心方式创建可用于Cypher表达式的自定义函数:Python用户定义函数(UDF) 和 C++扩展函数,以下是具体实现步骤:

一、Python用户定义函数(UDF)

适合快速开发、测试,无需编译步骤。

1. 编写Python函数

创建Python文件(例:custom_funcs.py),遵循Memgraph的UDF规范定义函数:

from mgp import mgp

# 只读函数:用于查询表达式,不修改数据
@mgp.read_proc
def multiply(a: int, b: int) -> int:
    return a * b

@mgp.read_proc
def str_concat(a: str, b: str) -> str:
    return f"{a}_{b}"

# 可写函数:用于修改图数据
@mgp.write_proc
def add_user_label(ctx: mgp.ProcCtx, node: mgp.Node, label: str) -> None:
    node.add_label(label)
  • 用@mgp.read_proc标记只读函数,可直接嵌入RETURN/WHERE等表达式
  • 用@mgp.write_proc标记可写函数,需通过CALL语句执行
  • 参数和返回值需指定类型,支持int、float、str、bool等基础类型,以及Node、Relationship等图对象

2. 加载模块

将Python文件放入Memgraph默认查询模块目录(/usr/lib/memgraph/query_modules/),然后执行Cypher命令热加载:

CALL mg.load_all();

3. 在Cypher中使用

只读函数直接用于表达式:

MATCH (n:Product {price: 20})
RETURN custom_funcs.multiply(n.price, 3) AS discounted_price;

可写函数通过CALL调用:

MATCH (u:User {name: "Bob"})
CALL custom_funcs.add_user_label(u, "VIP") YIELD *;

二、C++扩展函数

适合对性能要求高、需底层操作的场景。

1. 编写C++代码

创建C文件(例:custom_extension.cpp),使用Memgraph的C API:

#include <mgp.hpp>

namespace custom_extension {
void Multiply(mgp_list *args, mgp_graph *graph, mgp_result *result, mgp_memory *memory) {
  try {
    const auto a = mgp_value_get_int(mgp_list_at(args, 0));
    const auto b = mgp_value_get_int(mgp_list_at(args, 1));
    const auto product = a * b;
    mgp_result_set_value(result, mgp_value_make_int(product, memory));
  } catch (const std::exception &e) {
    mgp_result_set_error_msg(result, e.what());
  }
}

void RegisterModule(mgp_module *module, mgp_memory *memory) {
  auto multiply_proc = mgp_module_add_read_proc(module, "multiply", Multiply);
  mgp_proc_add_arg(multiply_proc, "a", mgp_type_int());
  mgp_proc_add_arg(multiply_proc, "b", mgp_type_int());
  mgp_proc_add_result(multiply_proc, "result", mgp_type_int());
}
}  // namespace custom_extension

extern "C" int mgp_init_module(struct mgp_module *module, struct mgp_memory *memory) {
  custom_extension::RegisterModule(module, memory);
  return 0;
}

extern "C" int mgp_shutdown_module() { return 0; }

2. 编译扩展

使用Memgraph的开发头文件编译为共享库:

g++ -fPIC -shared -o custom_extension.so custom_extension.cpp -I/usr/include/memgraph -lmgp

3. 加载扩展

将编译后的.so文件放入Memgraph默认扩展目录(/usr/lib/memgraph/extensions/),重启Memgraph服务即可加载。

4. 在Cypher中使用

直接嵌入表达式调用:

MATCH (n:Order {quantity: 5})
RETURN custom_extension.multiply(n.quantity, 10) AS total_units;

注意事项

  • 只读函数可直接用于RETURN、WHERE、SET等表达式,可写函数仅能通过CALL执行
  • 自定义函数命名需避开Memgraph内置函数名称
  • Python UDF支持热加载,无需重启服务;C++扩展需重启服务才能生效

内容的提问来源于stack exchange,提问作者GrandMel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:01:44