Cypher Shell

关于 Cypher Shell CLI

Cypher Shell 是一个命令行工具,用于针对 Neo4j 实例运行查询并执行管理任务。默认情况下,Shell 是交互式的;但你也可以通过在命令行直接传入 Cypher 语句或通过管道传输包含 Cypher 语句的文件(在 Windows 上需要 PowerShell)来将其用于脚本编写。它通过 Bolt 协议进行通信。

如果作为产品的一部分安装,Cypher Shell 位于 bin 目录下。或者,你也可以从 Neo4j 部署中心 下载并单独安装它。

语法

运行 Cypher Shell 的语法如下

cypher-shell [-h] [-a ADDRESS] [-u USERNAME] [--impersonate IMPERSONATE] [-p PASSWORD]
                    [--encryption {true,false,default}] [-d DATABASE] [--access-mode {read,write}]
                    [--enable-autocompletions] [--format {auto,verbose,plain}] [-P PARAM]
                    [--non-interactive] [--sample-rows SAMPLE-ROWS] [--wrap {true,false}] [-v]
                    [--driver-version] [-f FILE] [--change-password] [--log [LOG-FILE]]
                    [--history HISTORY-BEHAVIOUR] [--notifications] [--idle-timeout IDLE-TIMEOUT]
                    [--error-format {gql,legacy,stacktrace}]
                    [--transaction-timeout TRANSACTION-TIMEOUT] [--fail-fast | --fail-at-end]
                    [cypher]

位置参数

选项 描述

cypher

一个可选的 Cypher 字符串,用于执行后退出。

命名参数

选项 描述 默认

-h, --help

显示此帮助消息并退出。

--fail-fast

从文件读取时,在遇到第一个错误时退出并报告失败(这是默认行为)。

--fail-at-end

从文件读取时,在输入结束时退出并报告失败。

--enable-autocompletions

是否在 CLI 中启用 Cypher 自动补全。自动补全仅适用于 Neo4j 5 及更高版本。

false

--format {auto,verbose,plain}

所需的输出格式。如果以交互方式使用 Shell,结果将以表格格式显示;如果用于脚本编写,结果将以最简格式显示。
verbose 以表格格式显示结果并打印统计信息。
plain 以最简格式显示数据。

auto

-P PARAM, --param PARAM

为此会话添加参数。例如:-P '{a: 1}'-P '{a: 1, b: duration({seconds: 1})}'。此参数可以指定多次。

[]

--non-interactive

强制非交互模式。仅在自动检测失败(如在 Windows 上)时有用。

false

--sample-rows SAMPLE-ROWS

用于计算表格列宽的采样行数(仅适用于 format=VERBOSE)。

1000

--wrap {true,false}

如果表格列太窄,则换行显示列值(仅适用于 format=VERBOSE)。

true

-v, --version

打印 Cypher Shell 版本并退出。

false

--driver-version

打印 Neo4j 驱动程序版本并退出。

false

-f FILE, --file FILE

传入一个包含要执行的 Cypher 语句的文件。执行完所有语句后,Cypher Shell 将关闭。

--change-password

更改 neo4j 用户密码并退出。

false

--log [LOG-FILE], --debug [LOG-FILE]

启用日志记录到指定文件;如果省略文件名,则记录到标准错误输出。

--history HISTORY-BEHAVIOUR

2025.08 版本变更 查询和命令历史记录的文件路径;使用 in-memory 进行内存中历史记录,或使用 disable 禁用历史记录。如果省略此选项,历史记录将保存到 <user home>/.neo4j/.cypher_shell_history。也可以通过环境变量 NEO4J_CYPHER_SHELL_HISTORY 进行设置。

--notifications

在交互模式下启用通知。

false

--idle-timeout IDLE-TIMEOUT

在交互模式下,经过指定的空闲时间后关闭应用程序。你可以使用 <小时>h<分钟>m<秒>s 的格式指定持续时间,例如 1h(1 小时)、1h30m(1 小时 30 分钟)或 30m(30 分钟)。

disable

--error-format {gql,legacy,stacktrace}

控制错误信息的显示方式。

gql 2025.06 版本变更

--transaction-timeout TRANSACTION-TIMEOUT

2025.12 版本引入 事务超时。你可以使用 <小时>h<分钟>m<秒>s 的格式指定持续时间,例如 1h(1 小时)、1h30m(1 小时 30 分钟)或 30m(30 分钟)。

disable

连接参数

选项 描述 默认

-a ADDRESS, --address ADDRESS, --uri ADDRESS

要连接的地址和端口。默认为 neo4j://:7687。也可以使用环境变量 NEO4J_ADDRESSNEO4J_URI 指定。

neo4j://:7687

-u USERNAME, --username USERNAME

连接时使用的用户名。也可以使用环境变量 NEO4J_USERNAME 指定。

--impersonate IMPERSONATE

要模拟的用户。

-p PASSWORD, --password PASSWORD

连接时使用的密码。也可以使用环境变量 NEO4J_PASSWORD 指定。

--encryption {true,false,default}

是否应对到 Neo4j 的连接进行加密。此设置必须与 Neo4j 的配置保持一致。如果选择 'default',加密设置将根据指定的地址进行推断。例如,'neo4j+ssc' 协议会自动使用加密。

默认

-d DATABASE, --database DATABASE

要连接的数据库。也可以使用环境变量 NEO4J_DATABASE 指定。

--access-mode {read,write}

访问模式。默认为 WRITE(写入)。

write

在 Neo4j 发行版中运行 Cypher Shell

你可以通过运行 cypher-shell 并传入用户名和密码参数来连接到活动的 Neo4j DBMS

bin/cypher-shell -u neo4j -p <password>

输出如下

Connected to Neo4j at neo4j://:7687 as user neo4j.
Type :help for a list of available commands or :exit to exit the shell.
Note that Cypher queries must end with a semicolon.

从另一台服务器运行 Cypher Shell

你也可以将 Cypher Shell 工具安装在另一台服务器(非 Neo4j)上并连接到 Neo4j DBMS。Cypher Shell 需要 Java 21。

DEB 和 RPM 发行版如果尚未安装 Java,则会同时安装 Java 和 Cypher Shell 可执行文件。cypher-shell 文件与 Neo4j 在同一个 DEB/RPM Linux 存储库中提供。

TAR 发行版仅包含 cypher-shell 文件,因此你必须手动安装 Java。

  1. Neo4j 部署中心 下载 Cypher Shell。

  2. 通过运行 cypher-shell 命令并提供 Neo4j 地址、用户名和密码来连接到 Neo4j DBMS

    bin/cypher-shell -a neo4j://IP-address:7687 -u neo4j -p <password>

    输出如下

    Connected to Neo4j at neo4j://IP-address:7687 as user neo4j.
    Type :help for a list of available commands or :exit to exit the shell.
    Note that Cypher queries must end with a semicolon.

更改访问模式

默认情况下,访问模式设置为 write。但是,你可以在连接到 Neo4j DBMS 时使用 --access-mode 参数,或者在交互式 Shell 中使用 :access-mode 命令将访问模式更改为 readwrite。请记住,访问模式可能会影响查询被路由到集群中的哪些服务器。例如,带有 modeConstraint=SECONDARY 的服务器只能执行读取操作。

以下示例展示了如何在只读模式下连接到 Neo4j DBMS,然后在交互式 Shell 中将访问模式更改为写入模式。

  1. 在读取模式下连接到 Neo4j DBMS

    bin/cypher-shell -u neo4j -p <password> --access-mode read
    Connected to Neo4j using Bolt protocol version 5.4 at neo4j://:7687 as user neo4j.
    Type :help for a list of available commands or :exit to exit the shell.
    Note that Cypher queries must end with a semicolon.
  2. 尝试在只读访问模式下创建节点

    create ();
    Writing in read access mode not allowed. Attempted write to neo4j
  3. 在交互式 Shell 中将访问模式更改为写入

    :access-mode write
  4. 验证访问模式

    :access-mode
    Access mode write
  5. 在写入访问模式下创建节点

    create ();
    0 rows
    ready to start consuming query after 66 ms, results consumed after another 0 ms
    Added 1 nodes

有关 :access-mode 命令的更多信息,请在交互式 Shell 中运行以下命令

:help access-mode
usage: :access-mode - Display current access mode
:access-mode read - Reconnect with read access mode
:access-mode write - Reconnect with write access mode

可用命令

进入交互式 Shell 后,运行以下命令以显示所有可用命令

示例 1. 运行 help
:help

输出如下

Available commands:
  :access-mode  View or set access mode
  :begin        Open a transaction
  :commit       Commit the currently open transaction
  :connect      Connects to a database
  :disconnect   Disconnects from database
  :exit         Exit the logger
  :help         Show this help message
  :history      Statement history
  :impersonate  Impersonate user
  :param        Set the value of a query parameter
  :rollback     Rollback the currently open transaction
  :source       Executes Cypher statements from a file
  :sysinfo      Neo4j system information
  :use          Set the active database


For help on a specific command type:
    :help command

Keyboard shortcuts:
    Up and down arrows to access statement history.
    Tab for autocompletion of commands, hit twice to select suggestion from list using arrow keys.

For help on cypher please visit:
    /docs/cypher-manual/current/

运行 Cypher 语句

你可以通过以下方式运行 Cypher 语句

  • 直接在交互式 Shell 中输入 Cypher 语句。

  • 通过交互式 Shell 从文件运行 Cypher 语句。

  • 将 Cypher 语句文件作为 cypher-shell 参数运行。

本节中的示例使用 MATCH (n) RETURN n LIMIT 5 Cypher 语句,并将从数据库中返回 5 个节点。

示例 2. 直接在交互式 Shell 中输入 Cypher 语句
MATCH (n) RETURN n LIMIT 5;

以下两个示例假设运行 cypher-shell 命令的文件夹中存在一个名为 example.cypher 的文件,其内容如下

MATCH (n) RETURN n LIMIT 5;
示例 3. 通过交互式 Shell 从文件运行 Cypher 语句

在 Cypher 交互式 Shell 中,你可以使用 :source 命令后跟文件名来运行该文件中的 Cypher 语句

:source /path/to/your/example.cypher
示例 4. 将 Cypher 语句文件作为 cypher-shell 参数运行。

运行 cypher-shell 时,可以将包含 Cypher 语句的文件作为参数传递。

此处的示例使用 --format plain 标志以获取简单输出。

使用 cat (UNIX)

cat example.cypher | bin/cypher-shell -u neo4j -p <password> --format plain

使用 type (Windows)

type example.cypher | bin/cypher-shell.bat -u neo4j -p <password> --format plain

查询参数

Cypher Shell 支持基于参数的查询。使用 :param <Cypher Map> 设置参数,或使用旧的箭头语法 :param name ⇒ <Cypher Expression>。使用箭头语法时,表达式限制为单行。使用 :param 列出当前参数。使用 :param clear 清除参数。

参数可以设置为任何 Cypher 表达式。某些表达式需要在线评估并需要一个打开的会话。参数表达式仅评估一次。例如,:param {now: datetime()} 会将参数 now 设置为设置参数时的当前日期和时间。

示例 5. 在 Cypher Shell 中使用参数
  1. 使用 :param 关键字将参数 alias 设置为 Robin,将 born 设置为 date('1940-03-20')

    :param {alias: 'Robin', born: date('1940-03-20')}
  2. 使用 :params 关键字检查当前参数

    :param
    {
      alias: 'Robin',
      born: date('1981-08-01')
    }
  3. 现在在 Cypher 查询中使用 aliasborn 参数

    CREATE (:Person {name : 'Dick Grayson', alias : $alias, born: $born });
    Added 1 nodes, Set 3 properties, Added 1 labels
  4. 验证结果

    MATCH (n) RETURN n;
    +--------------------------------------------------------------------+
    | n                                                                  |
    +--------------------------------------------------------------------+
    | (:Person {name: "Bruce Wayne", alias: "Batman"})                   |
    | (:Person {name: "Selina Kyle", alias: ["Catwoman", "The Cat"]})    |
    | (:Person {name: "Dick Grayson", alias: "Robin", born: 1940-03-20}) |
    +--------------------------------------------------------------------+
    3 rows available after 2 ms, consumed after another 2 ms

事务

Cypher Shell 支持显式和隐式事务。事务状态使用关键字 :begin:commit:rollback 进行控制。

从 Cypher Shell 运行的显式和隐式事务都将附加默认的事务元数据,遵循约定(参见 附加元数据到事务)。

示例 6. 使用细粒度事务控制

该示例使用内置 Neo4j Browser 指南中提供的 Movie Graph 数据集。

  1. 运行查询,显示数据库中只有一个出生于 1964 年的人。

    MATCH (n:Person) WHERE n.born=1964 RETURN n.name AS name;
    +----------------+
    | name           |
    +----------------+
    | "Keanu Reeves" |
    +----------------+
    
    1 row
    ready to start consuming query after 9 ms, results consumed after another 0 ms
  2. 开始一个事务并创建另一个出生于同一年的人

    :begin
    neo4j# CREATE (:Person {name : 'Edward Mygma', born:1964});
    0 rows
    ready to start consuming query after 38 ms, results consumed after another 0 ms
    Added 1 nodes, Set 2 properties, Added 1 labels
  3. 如果你打开第二个 Cypher Shell 会话并运行步骤 1 中的查询,你会注意到最新的 CREATE 语句没有任何更改。

    MATCH (n:Person) WHERE n.born=1964 RETURN n.name AS name;
    +----------------+
    | name           |
    +----------------+
    | "Keanu Reeves" |
    +----------------+
    
    1 row
    ready to start consuming query after 9 ms, results consumed after another 0 ms
  4. 回到第一个会话并提交事务。

    neo4j# :commit
  5. 现在,如果你运行步骤 1 中的查询,你会看到 Edward Mygma 已被添加到数据库中。

    MATCH (n:Person) WHERE n.born=1964 RETURN n.name AS name;
    +----------------+
    | name           |
    +----------------+
    | "Keanu Reeves" |
    | "Edward Mygma" |
    +----------------+
    
    2 rows
    ready to start consuming query after 1 ms, results consumed after another 1 ms

事务超时

你可以使用特定的事务超时启动 Cypher Shell,这将应用于会话期间的所有事务。

示例 7. 使用事务超时参数启动
bin/cypher-shell -u neo4j -p <password> --transaction-timeout 10m

执行一个非常耗时的查询。

UNWIND range(0, 90_000) AS x
CALL apoc.util.sleep(100)
RETURN sum(x) AS sum;

大约 10 分钟后,事务超时。

25N14: invalid transaction state - transaction termination client error. The transaction has been terminated. Retry your operation in a new transaction, and you should see a successful result. Reason: The transaction has not completed within the timeout specified at its start by the client. You may want to retry with a longer timeout.

存储过程

Cypher Shell 支持运行当前用户有权使用的任何存储过程。

示例 8. 调用 dbms.showCurrentUser 存储过程
CALL dbms.showCurrentUser();
+------------------------------+
| username | roles     | flags |
+------------------------------+
| "neo4j"  | ["admin"] | []    |
+------------------------------+

1 row available after 66 ms, consumed after another 2 ms

支持的操作系统

你可以在 Windows 系统上通过 cmd,以及在 Unix 系统上通过 bash 使用 Cypher Shell CLI。

其他 Shell 可能按预期工作,但没有测试覆盖率来保证兼容性。

键盘快捷键

以下键盘命令可在交互模式下使用。

操作

↑ 和 ↓(箭头键)

访问语句历史记录。

↹ (Tab 键)

命令和 Cypher 语法的自动补全。对 Cypher 语法的建议尚不完整。

Home (键)

将光标移动到当前行的第一个字符。

End (键)

将光标移动到当前行的最后一个字符。