本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
Neptune 中的 Gremlin 事务
Gremlin 事务的执行上下文有多种。在与 Gremlin 结合使用时,务必了解您所处的上下文及其影响:
-
Script-based
– 使用基于文本的 Gremlin 字符串发出请求,如下所示:使用 Java 驱动程序和
Client.submit(
。string
)使用 Gremlin 控制台和
:remote connect
。使用 HTTP API。
-
Bytecode-based
– 请求是使用 Gremlin 语言变体(GLV) 中典型的序列化的 Gremlin 字节码发出的。 例如,使用 Java 驱动程序
g = traversal().withRemote(
。...
)
对于上述任一上下文,都有额外的上下文,即请求以无会话或绑定到会话的形式发送。
注意
Gremlin 事务必须始终提交或回滚,这样才能释放服务器端资源。如果在交易过程中出现错误,请务必重试整个事务,而不仅仅是失败的特定请求。
无会话请求
无会话时,请求等同于单个事务。
对于脚本来说,这意味着在单个请求中发送的一条或多条 Gremlin 语句将作为单个事务提交或回滚。例如:
Cluster cluster = Cluster.open(); Client client = cluster.connect(); // sessionless // 3 vertex additions in one request/transaction: client.submit("g.addV();g.addV();g.addV()").all().get();
对于字节码,会对从 g
生成和执行的每个遍历发出无会话请求:
GraphTraversalSource g = traversal().withRemote(
...
); // 3 vertex additions in three individual requests/transactions: g.addV().iterate(); g.addV().iterate(); g.addV().iterate(); // 3 vertex additions in one single request/transaction: g.addV().addV().addV().iterate();
绑定到会话的请求
绑定到会话时,可以在单个事务的上下文中应用多个请求。
对于脚本来说,这意味着没有必要将所有图形操作串联成单个嵌入式字符串值:
Cluster cluster = Cluster.open(); Client client = cluster.connect(sessionName); // session try { // 3 vertex additions in one request/transaction: client.submit("g.addV();g.addV();g.addV()").all().get(); } finally { client.close(); } try { // 3 vertex additions in three requests, but one transaction: client.submit("g.addV()").all().get(); // starts a new transaction with the same sessionName client.submit("g.addV()").all().get(); client.submit("g.addV()").all().get(); } finally { client.close(); }
对于字节码,之后 TinkerPop 3.5.x
,可以显式控制事务并透明地管理会话。Gremlin 语言变体 (GLV) 支持 Gremlin 对事务执行 commit()
或 rollback()
的 tx()
语法,如下所示:
GraphTraversalSource g = traversal().withRemote(conn); Transaction tx = g.tx(); // Spawn a GraphTraversalSource from the Transaction. // Traversals spawned from gtx are executed within a single transaction. GraphTraversalSource gtx = tx.begin(); try { gtx.addV('person').iterate(); gtx.addV('software').iterate(); tx.commit(); } finally { if (tx.isOpen()) { tx.rollback(); } }
尽管上面的示例是用 Java 编写的,但您也可以在 Python、Javascript 和 .NET 中使用这种 tx()
语法。
警告
无会话只读查询在 SNAPSHOT 隔离下执行,但在显式事务中运行的只读查询则在 SERIALIZABLE 隔离下执行。与在 SNAPSHOT
隔离下运行的只读查询不同,在 SERIALIZABLE
隔离下执行的只读查询会产生更高的开销,并且可能阻塞并发写入或被并发写入阻塞。