学习来源:https://github.com/dgraph-io/pydgraph
dgraph说明文档https://dgraph.io/docs/get-started/
安装pydgraph
pip install pydgraph
官方文档说明,为了避免在添加复合凭据或使用客户端授权时出现问题,请安装gRPC 1.19.0版本:
pip install grpcio==1.19.0
我直接pip install grpcio了,没设置版本
安装完成后在自己的环境中验证一下是否安装成功
import pydgraph
pydgraph.VERSION
连接到dgraph
链接dgraph之前先启动zero和alpha,ratel可以做实验的时候查看效果用
启动之后创建client_stub和client,类似py2neo里的Graph连接到neo4j
client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
删除dgraph中所有数据
client.alter(pydgraph.Operation(drop_all=True))
创建SCHEMA
schema = """
name: string @index(exact) .
friend: [uid] @reverse .
age: int .
married: bool .
loc: geo .
dob: datetime .
type Person {
name
friend
age
married
loc
dob
}
"""
client.alter(pydgraph.Operation(schema=schema))
这里的schema和dgraph中编辑的schema是相同格式的(注意三引号,否则报错)
Edit Schema File
用rdf格式创建数据
后几行()小括号里面的是边属性,不可设置中文
txbb = '''
<_:person001> <name> "丁丁" .
<_:person001> <'颜色'> "紫色" .
<_:person001> <antenna_shape> "三角形" .
<_:person001> <height> "304" .
<_:person002> <name> "迪西" .
<_:person002> <color> "绿色" .
<_:person002> <antenna_shape> "直线形" .
<_:person002> <height> "259" .
<_:person003> <name> "拉拉" .
<_:person003> <color> "黄色" .
<_:person003> <antenna_shape> "螺旋" .
<_:person002> <height> "245" .
<_:person004> <name> "小波" .
<_:person004> <color> "红色" .
<_:person004> <antenna_shape> "圆形" .
<_:person004> <height> "182" .
<_:person001> <'朋友'> <_:person002> (friendship=1.0) .
<_:person001> <friend> <_:person003> (friendship=0.9) .
<_:person001> <friend> <_:person004> (friendship=0.8) .
<_:person002> <friend> <_:person003> .
<_:person002> <friend> <_:person004> .
<_:person003> <friend> <_:person004> .
'''
txn = client.txn()
txn.mutate(set_nquads=txbb)
txn.commit()
用json格式创建数据
def create_data(client):
# Create a new transaction.
txn = client.txn()
try:
# Create data.
p = {
'uid': '_:alice',
'dgraph.type': 'Person',
'name': 'Alice',
'age': 26,
'married': True,
'loc': {
'type': 'Point',
'coordinates': [1.1, 2],
},
'dob': datetime.datetime(1980, 1, 1, 23, 0, 0, 0).isoformat(),
'friend': [
{
'uid': '_:bob',
'dgraph.type': 'Person',
'name': 'Bob',
'age': 24,
}
],
'school': [
{
'name': 'Crown Public School',
}
]
}
# Run mutation.
response = txn.mutate(set_obj=p)
# Commit transaction.
txn.commit()
# Get uid of the outermost object (person named "Alice").
# response.uids returns a map from blank node names to uids.
print('Created person named "Alice" with uid = {}'.format(response.uids['alice']))
finally:
# Clean up. Calling this after txn.commit() is a no-op and hence safe.
txn.discard()
边属性在json中设置格式:(例如上例中friend关系)
'friend': [
{
'uid': '_:bob',
'dgraph.type': 'Person',
'name': 'Bob',
'age': 24,
'friend|boyfriend': True,
}
],
删除数据
def delete_data(client):
# Create a new transaction.
txn = client.txn()
try:
query1 = """query all($a: string) {
all(func: eq(name, $a)) {
uid
}
}"""
variables1 = {'$a': 'Bob'}
res1 = client.txn(read_only=True).query(query1, variables=variables1)
ppl1 = json.loads(res1.json)
for person in ppl1['all']:
print("Bob's UID: " + person['uid'])
txn.mutate(del_obj=person)
print('Bob deleted')
txn.commit()
finally:
txn.discard()
查询数据
数据以字典的格式返回
def query_alice(client):
# Run query.
query = """query all($a: string) {
all(func: eq(name, $a)) {
uid
name
age
married
loc
dob
friend {
name
age
}
school {
name
}
}
}"""
variables = {'$a': 'Alice'}
res = client.txn(read_only=True).query(query, variables=variables)
ppl = json.loads(res.json)
# Print results.
print('Number of people named "Alice": {}'.format(len(ppl['all'])))
return ppl
查询并添加数据
query = """{
u as var(func: eq(name, "Alice"))
}"""
nquad = """
uid(u) <name> "Alice" .
uid(u) <age> "25" .
<_:tom> <name> "Tom" .
uid(u) <boyfriend> <_:tom> (love=1) .
"""
txn = client.txn()
mutation = txn.create_mutation(set_nquads=nquad)
request = txn.create_request(query=query, mutations=[mutation], commit_now=True)
txn.do_request(request)