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

如何获取Dgraph事务的start_ts与commit_ts?含pydgraph实操疑问

如何获取Dgraph事务的开始与提交时间戳(多事务客户端会话场景)

环境说明

  • Docker镜像:docker pull dgraph/dgraph:latest # version:v23.1.0
  • 依赖:pydgraph-23.0.1、Python v3.8.18
  • 测试操作:基于官方simple.py修改,将localhost替换为175.27.241.31,在第78行后添加print(response),但响应仅返回事务的start_ts,未出现commit_ts,响应示例如下:

txn {
start_ts: 260380056
keys: ...
...
preds: ...
...
}
latency {
...
}
metrics {
...
}
uids {
...
}


具体疑问解答

1. 如何通过pydgraph获取事务的commit_ts?

在pydgraph中,事务提交后,对应的Txn对象会自动填充commit_ts属性,需在调用txn.commit()之后访问该属性。

修改simple.py中的事务操作代码示例:

def create_data(client):
    alice = {
        "name": "Alice",
        "age": 28,
        "married": True,
        "loc": {"type": "Point", "coordinates": [1.1, 2.2]},
        "dob": "1990-01-01",
        "friends": [{"name": "Bob", "age": 29}]
    }

    txn = client.txn()
    try:
        # 执行突变
        response = txn.mutate(set_obj=alice)
        # 提交事务
        txn.commit()
        # 获取时间戳
        print(f"事务开始时间戳: {txn.start_ts}")
        print(f"事务提交时间戳: {txn.commit_ts}")
        return response
    except Exception as e:
        txn.discard()
        raise e

参考依据:pydgraph的Txn类源码中,commit()方法会将服务端返回的提交时间戳赋值给txn.commit_ts;官方文档可查看pydgraph API参考中Txn类的属性说明。

2. simple.py中的代码是否表示客户端逐个执行多个事务?

是的。这段代码中的每个数据操作(drop_all、set_schema、create_data、delete_data等)都对应独立的Dgraph事务:

  • drop_all、set_schema内部会创建临时事务并执行提交;
  • create_data、delete_data显式创建Txn对象,完成操作后提交或丢弃事务。
    客户端会按代码顺序逐个执行这些事务,前一个事务完成(提交/丢弃)后才会触发下一个操作。

3. 除pydgraph外的其他获取方式

方法1:分析Dgraph Alpha节点日志

启动Alpha节点时添加--v=2参数开启详细日志,日志中会记录每个事务的开始与提交时间戳,示例日志行:

I0101 12:00:00.000000 12345 txn.go:123] Committed txn with start_ts=260380056, commit_ts=260380057

方法2:使用Dgraph HTTP API

通过HTTP接口提交事务,提交成功后响应会包含start_ts和commit_ts,Python示例代码:

import requests

# 提交突变并立即提交事务
url = "http://175.27.241.31:8080/mutate?commitNow=true"
headers = {"Content-Type": "application/json"}
payload = {
    "set": [
        {"name": "Alice", "age": 28}
    ]
}

response = requests.post(url, json=payload, headers=headers)
result = response.json()

print(f"Start TS: {result['txn']['start_ts']}")
print(f"Commit TS: {result['txn']['commit_ts']}")

方法3:使用Dgraph CLI

通过dgraph mutate命令提交事务,命令执行后会输出事务时间戳信息,示例命令:

dgraph mutate -f data.json -a http://175.27.241.31:8080 --commit-now

执行后输出会包含事务的开始与提交时间戳。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:26:14