學(xué)習(xí)來源:https://github.com/dgraph-io/pydgraph
dgraph說明文檔https://dgraph.io/docs/get-started/
安裝pydgraph
pip install pydgraph
官方文檔說明骚亿,為了避免在添加復(fù)合憑據(jù)或使用客戶端授權(quán)時出現(xiàn)問題沪哺,請安裝gRPC 1.19.0版本:
pip install grpcio==1.19.0
我直接pip install grpcio了漫雷,沒設(shè)置版本
安裝完成后在自己的環(huán)境中驗(yàn)證一下是否安裝成功
import pydgraph
pydgraph.VERSION
連接到dgraph
鏈接dgraph之前先啟動zero和alpha湃崩,ratel可以做實(shí)驗(yàn)的時候查看效果用
啟動之后創(chuàng)建client_stub和client,類似py2neo里的Graph連接到neo4j
client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
刪除dgraph中所有數(shù)據(jù)
client.alter(pydgraph.Operation(drop_all=True))
創(chuàng)建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是相同格式的(注意三引號银择,否則報(bào)錯)
Edit Schema File
用rdf格式創(chuàng)建數(shù)據(jù)
后幾行()小括號里面的是邊屬性斑司,不可設(shè)置中文
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格式創(chuàng)建數(shù)據(jù)
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中設(shè)置格式:(例如上例中friend關(guān)系)
'friend': [
{
'uid': '_:bob',
'dgraph.type': 'Person',
'name': 'Bob',
'age': 24,
'friend|boyfriend': True,
}
],
刪除數(shù)據(jù)
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()
查詢數(shù)據(jù)
數(shù)據(jù)以字典的格式返回
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
查詢并添加數(shù)據(jù)
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)