pydgraph學(xué)習(xí)

學(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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末妙蔗,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子免猾,更是在濱河造成了極大的恐慌是辕,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件猎提,死亡現(xiàn)場離奇詭異获三,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)锨苏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門疙教,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人伞租,你說我怎么就攤上這事贞谓。” “怎么了葵诈?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵裸弦,是天一觀的道長。 經(jīng)常有香客問我作喘,道長理疙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任泞坦,我火速辦了婚禮沪斟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己主之,他們只是感情好择吊,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著槽奕,像睡著了一般几睛。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上粤攒,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天所森,我揣著相機(jī)與錄音,去河邊找鬼夯接。 笑死焕济,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的盔几。 我是一名探鬼主播晴弃,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼逊拍!你這毒婦竟也來了上鞠?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤芯丧,失蹤者是張志新(化名)和其女友劉穎芍阎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缨恒,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡谴咸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了骗露。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片寿冕。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖椒袍,靈堂內(nèi)的尸體忽然破棺而出驼唱,到底是詐尸還是另有隱情,我是刑警寧澤驹暑,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布玫恳,位于F島的核電站,受9級特大地震影響优俘,放射性物質(zhì)發(fā)生泄漏京办。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一帆焕、第九天 我趴在偏房一處隱蔽的房頂上張望惭婿。 院中可真熱鬧不恭,春花似錦、人聲如沸财饥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽钥星。三九已至沾瓦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谦炒,已是汗流浹背贯莺。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宁改,地道東北人缕探。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像还蹲,于是被迫代替她去往敵國和親爹耗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容