1. 程式人生 > 其它 >圖資料庫dgraph 的安裝和使用

圖資料庫dgraph 的安裝和使用

技術標籤:資料庫


dgraph 新增資料或修改刪除資料叫一個突變
查詢叫一個查詢

新增插入資料

dgraph 支援用json格式插入資料 新增資料

#post 請求 直接呼叫突變API http://localhost:8080/mutate?commitNow=true

{
  "set":[
    {
      "name": "劉備",
      "age": 40,
      "usernameOFen":"liubei",
      "follows": {
        "name": "孫尚香",
        "age": 28,
        "follows":{
          "name": "Leyla",
          "age": 31
        }
      }
    }
  ]
}

新增索引 以上的name欄位設定為索引

curl 192.168.1.172:8080/alter -XPOST -d $' name: string @index(term) .'

修改資料 同樣呼叫突變介面
通過查詢得知孫尚香的dgraph 給 孫尚香分配的uid 是0x2711
新增張飛為孫尚香的朋友

{
"set":[{
"uid":"0x2711",
"friends":
    {
  "name":"張飛",
  "age":"20",
  "money":"10",
  "usernameOFen":"zhangfei"
    }}]}

新增關羽為劉備的朋友 friends

{
"set":[{
"uid":"0x2713",
"money":"10",
"friends":
    {
  "name":"關羽",
  "age":"27",
  "money":"888",
  "usernameOFen":"guanyu"
    }}]}

用python 查詢dgraph 已有資料

import json

import pydgraph
import time
import logging

logger = logging.getLogger(__name__)

# Create a client stub.
client_stub = pydgraph.DgraphClientStub('192.168.1.172:9080')
# Create a client.
client = pydgraph.DgraphClient(client_stub)
## dgraph 資料庫根據索引 查詢相應資料
def atest_query_edge_attr():
    query = '''{
  friends_data(func:eq(name,"劉備")){
    uid
    name
    age
    money
    friends{
        name
        age
        uid
        money
        usernameOFen
        }
    usernameOFen
    follows{
        name
        age
        uid
        friends{
            name
            age
            uid
            money
            usernameOFen
        }
    }
  }
}'''

    variables = {}
    res = client.txn(read_only=False).query(query, variables=variables)
    ppl = json.loads(res.json)
    all = ppl['friends_data']
    #print(f'query: {all}')
    print(ppl)
  
atest_query_edge_attr()
------------------->>>>
{'friends_data': [{'uid': '0x2713', 'name': '劉備', 'age': 40, 'money': '10', 'friends': {'name': '關羽', 'age': 27, 'uid': '0x2715', 'money': '888', 'usernameOFen': 'guanyu'}, 'usernameOFen': 'liubei', 'follows': {'name': '孫尚香', 'age': 28, 'uid': '0x2711', 'friends': {'name': '張飛', 'age': 20, 'uid': '0x2714', 'money': '10', 'usernameOFen': 'zhangfei'}}}]}