ahopkins
(Adam Hopkins)
August 29, 2018, 3:36pm
1
So… I’m just curious to hear how other people are interacting with dgraph. I’m interested to know if people are connecting directly with http or rpc… or if they are using a driver inside a programming language. And, if so, what language?
In part it’s because I’m working on my own package (read more ), and I’d like to get a better understanding of the community’s adoption and usage. Mostly… I’m just curious. The more I use dgraph, the more I like it.
import json
import pydgraph
import requests
from grpc import insecure_channel
# Constants
DGRAPH_GRPC_HOST = "localhost:9080" # Alpha gRPC endpoint
DGRAPH_HTTP_HOST = "http://localhost:8080" # Alpha HTTP endpoint
# Setup gRPC client with pydgraph
def create_grpc_client():
channel = insecure_channel(DGRAPH_GRPC_HOST)
return pydgraph.DgraphClient(pydgraph.DgraphClientStub(channel))
# HTTP helper function
def http_request(endpoint, payload, method="POST"):
headers = {"Content-Type": "application/json"}
url = f"{DGRAPH_HTTP_HOST}{endpoint}"
if method == "POST":
resp = requests.post(url, data=json.dumps(payload), headers=headers)
elif method == "GET":
resp = requests.get(url, params=payload, headers=headers)
resp.raise_for_status()
return resp.json()
# Set schema (same for both methods)
def set_schema(client):
schema = """
type User {
name: string
follows: [User]
}
name: string @index(exact) .
follows: [uid] .
"""
# gRPC
op = pydgraph.Operation(schema=schema)
client.alter(op)
# HTTP (equivalent)
http_request("/alter", {"schema": schema})
# Insert data (example: users and follows)
def insert_data(client):
# Data as JSON
txn = client.txn()
try:
mutation = {
"set": [
{"name": "alice", "dgraph.type": "User"},
{"name": "bob", "dgraph.type": "User"},
{"name": "alice", "follows": [{"name": "bob"}]}
]
}
# gRPC
mu = pydgraph.Mutation(set_json=json.dumps(mutation).encode('utf-8'))
txn.mutate(mu, commit_now=True)
# HTTP (equivalent)
http_request("/mutate?commitNow=true", mutation)
finally:
txn.discard()
# Query data
def query_data(client):
query = """
{
users(func: eq(name, "alice")) {
uid
name
follows {
uid
name
}
}
}
"""
# gRPC
resp_grpc = client.txn(read_only=True).query(query)
result_grpc = json.loads(resp_grpc.json)
print("gRPC Result:", json.dumps(result_grpc, indent=2))
# HTTP
resp_http = http_request("/query", {"query": query}, method="POST")
print("HTTP Result:", json.dumps(resp_http, indent=2))
def main():
# Initialize gRPC client
client = create_grpc_client()
# Setup schema
print("Setting schema...")
set_schema(client)
# Insert data
print("Inserting data...")
insert_data(client)
# Query data
print("Querying data...")
query_data(client)
if __name__ == "__main__":
main()