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

技术咨询:Memgraph是否支持WebSocket连接?求最小实现代码

Memgraph的WebSocket连接支持及最小代码示例

Memgraph支持通过WebSocket连接,采用的是Bolt协议通过WebSocket传输(即Bolt over WebSocket),默认监听端口为7688(普通Bolt协议端口为7687),该功能默认启用,可通过配置文件调整端口或禁用。

以下是Node.js环境下的最小代码示例:

  1. 先安装依赖库:
npm install ws bolt-protocol
  1. 连接并执行查询的代码:
const WebSocket = require('ws');
const bolt = require('bolt-protocol');

// 建立WebSocket连接到Memgraph
const ws = new WebSocket('ws://localhost:7688');

// 初始化Bolt协议处理器
const boltProtocol = bolt({
  onMessage: msg => ws.send(msg),
  onError: err => console.error('Bolt协议错误:', err),
  onClose: () => ws.close()
});

// 连接打开后初始化Bolt会话
ws.on('open', () => {
  boltProtocol.initialize({ user_agent: 'memgraph-ws-example' });
});

// 接收WebSocket消息并交给Bolt协议处理
ws.on('message', data => {
  boltProtocol.process(data);
});

// 执行Cypher查询
boltProtocol.run('MATCH (n) RETURN n LIMIT 3', {}, (err, records) => {
  if (err) {
    console.error('查询失败:', err);
    return;
  }
  console.log('查询结果:', records);
  // 关闭会话
  boltProtocol.close();
});

如果是浏览器环境,可直接使用原生WebSocket对象,搭配bolt-protocol库(需通过CDN引入或打包工具处理),逻辑与上述示例一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:31:06