Dgraph
Distributed Graph Database
A GraphQL-native distributed graph database. Supports horizontal scaling, ACID transactions, and real-time subscriptions, and is optimized for processing large-scale connected data.
Distributed Graph Database
A GraphQL-native distributed graph database. Supports horizontal scaling, ACID transactions, and real-time subscriptions, and is optimized for processing large-scale connected data.
Dgraph is an open-source distributed graph database developed in the Go language. It was created by engineers formerly of Google and was designed as a distributed system from the start, so it can handle petabyte-scale graph data.
Native GraphQL support is its key feature. When you define a schema in GraphQL, a CRUD API is generated automatically. It provides a GraphQL endpoint directly from the database without building a separate GraphQL server.
DQL (Dgraph Query Language) is a query language that extends GraphQL and is optimized for graph traversal, aggregation, and filtering. It handles recursive queries and complex joins efficiently, and also supports regular expressions, geospatial queries, and full-text search.
Distributed architecture consists of Zero (cluster coordination), Alpha (data storage/queries), and Ratel (UI). Data is automatically sharded and replicated, and consistency is guaranteed by the Raft consensus algorithm. Performance can be scaled linearly simply by adding nodes.
It is well suited to relationship-centric data analysis such as social networks, recommendation engines, knowledge graphs, and fraud detection.
# Dgraph Python 클라이언트 (pydgraph)
import pydgraph
import json
# 클라이언트 연결
client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
def set_schema():
"""GraphQL 스키마 설정"""
schema = """
type Person {
name: string @index(exact, term) .
age: int @index(int) .
email: string @index(exact) @upsert .
friends: [Person] @reverse .
works_at: Company .
}
type Company {
name: string @index(exact) .
industry: string @index(term) .
employees: [Person] @reverse .
}
"""
op = pydgraph.Operation(schema=schema)
client.alter(op)
print("스키마 설정 완료")
def create_data():
"""데이터 삽입"""
txn = client.txn()
try:
# JSON 형식으로 데이터 생성
data = {
"uid": "_:alice",
"dgraph.type": "Person",
"name": "Alice",
"age": 28,
"email": "alice@example.com",
"friends": [
{
"uid": "_:bob",
"dgraph.type": "Person",
"name": "Bob",
"age": 32,
"email": "bob@example.com"
},
{
"uid": "_:charlie",
"dgraph.type": "Person",
"name": "Charlie",
"age": 25,
"email": "charlie@example.com"
}
],
"works_at": {
"uid": "_:techcorp",
"dgraph.type": "Company",
"name": "TechCorp",
"industry": "Technology"
}
}
response = txn.mutate(set_obj=data)
txn.commit()
# 생성된 UID 확인
print("생성된 노드:")
for key, uid in response.uids.items():
print(f" {key}: {uid}")
return response.uids
finally:
txn.discard()
def query_friends():
"""친구 관계 쿼리 (DQL)"""
query = """
{
person(func: eq(name, "Alice")) {
uid
name
age
friends {
name
age
email
}
works_at {
name
industry
}
}
}
"""
txn = client.txn(read_only=True)
try:
response = txn.query(query)
result = json.loads(response.json)
print("\nAlice의 정보:")
for person in result.get('person', []):
print(f" 이름: {person['name']}, 나이: {person['age']}")
print(f" 회사: {person.get('works_at', {}).get('name', 'N/A')}")
print(" 친구들:")
for friend in person.get('friends', []):
print(f" - {friend['name']} ({friend['age']}세)")
finally:
txn.discard()
def query_with_variables():
"""변수를 사용한 쿼리"""
query = """
query findPerson($name: string, $minAge: int) {
person(func: eq(name, $name)) @filter(ge(age, $minAge)) {
uid
name
age
friends @filter(ge(age, $minAge)) {
name
age
}
}
}
"""
variables = {"$name": "Alice", "$minAge": "25"}
txn = client.txn(read_only=True)
try:
response = txn.query(query, variables=variables)
result = json.loads(response.json)
print(f"\n쿼리 결과: {json.dumps(result, indent=2, ensure_ascii=False)}")
finally:
txn.discard()
def upsert_example():
"""Upsert (있으면 업데이트, 없으면 삽입)"""
query = """
{
user as var(func: eq(email, "alice@example.com"))
}
"""
mutation = """
uid(user) "29" .
uid(user) "%s" .
""" % "2024-01-15T10:30:00Z"
txn = client.txn()
try:
request = pydgraph.Request(
query=query,
mutations=[pydgraph.Mutation(set_nquads=mutation)],
commit_now=True
)
response = client.txn().do_request(request)
print("\nUpsert 완료")
finally:
txn.discard()
# 실행
if __name__ == "__main__":
set_schema()
uids = create_data()
query_friends()
query_with_variables()
upsert_example()
# 연결 종료
client_stub.close()
// Dgraph Node.js 클라이언트 (dgraph-js)
const dgraph = require('dgraph-js');
const grpc = require('@grpc/grpc-js');
// 클라이언트 연결
const clientStub = new dgraph.DgraphClientStub(
'localhost:9080',
grpc.credentials.createInsecure()
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
async function setSchema() {
const schema = `
type Person {
name: string @index(exact, term) .
age: int @index(int) .
email: string @index(exact) @upsert .
friends: [Person] @reverse .
}
`;
const op = new dgraph.Operation();
op.setSchema(schema);
await dgraphClient.alter(op);
console.log('스키마 설정 완료');
}
async function createData() {
const txn = dgraphClient.newTxn();
try {
const data = {
uid: '_:alice',
'dgraph.type': 'Person',
name: 'Alice',
age: 28,
email: 'alice@example.com',
friends: [
{
uid: '_:bob',
'dgraph.type': 'Person',
name: 'Bob',
age: 32,
email: 'bob@example.com'
}
]
};
const mu = new dgraph.Mutation();
mu.setSetJson(data);
mu.setCommitNow(true);
const response = await txn.mutate(mu);
console.log('생성된 UID:', response.getUidsMap().toObject());
return response.getUidsMap();
} finally {
await txn.discard();
}
}
async function queryData() {
const query = `
{
people(func: has(name), orderasc: name) {
uid
name
age
email
friends {
name
age
}
}
}
`;
const txn = dgraphClient.newTxn({ readOnly: true });
try {
const response = await txn.query(query);
const result = response.getJson();
console.log('\n전체 사용자:');
result.people.forEach(person => {
console.log(` ${person.name} (${person.age}세)`);
if (person.friends) {
person.friends.forEach(friend => {
console.log(` → ${friend.name}`);
});
}
});
} finally {
await txn.discard();
}
}
async function graphqlMutation() {
// GraphQL 엔드포인트 사용 (HTTP)
const fetch = require('node-fetch');
const mutation = `
mutation AddPerson($input: AddPersonInput!) {
addPerson(input: [$input]) {
person {
uid
name
age
}
}
}
`;
const variables = {
input: {
name: 'David',
age: 35,
email: 'david@example.com'
}
};
const response = await fetch('http://localhost:8080/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: mutation, variables })
});
const result = await response.json();
console.log('\nGraphQL 뮤테이션 결과:', result);
}
async function subscriptionExample() {
// 실시간 구독 (WebSocket)
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const client = new SubscriptionClient(
'ws://localhost:8080/graphql',
{ reconnect: true },
ws
);
const subscription = `
subscription WatchPeople {
queryPerson {
name
age
}
}
`;
client.request({ query: subscription }).subscribe({
next: data => console.log('변경 감지:', data),
error: err => console.error('구독 오류:', err)
});
}
// 실행
(async () => {
await setSchema();
await createData();
await queryData();
await graphqlMutation();
clientStub.close();
})();
# ============================================
# GraphQL 스키마 정의
# ============================================
type Person {
id: ID!
name: String! @search(by: [exact, term])
age: Int @search(by: [int])
email: String! @id # 유니크 식별자
friends: [Person] @hasInverse(field: friends)
posts: [Post] @hasInverse(field: author)
}
type Post {
id: ID!
title: String! @search(by: [fulltext])
content: String
author: Person!
tags: [String] @search(by: [exact])
createdAt: DateTime!
}
# ============================================
# GraphQL 쿼리 예제
# ============================================
# 모든 사용자와 친구 조회
query {
queryPerson {
name
age
friends {
name
}
}
}
# 필터링과 페이지네이션
query {
queryPerson(
filter: { age: { ge: 25 } }
order: { asc: name }
first: 10
offset: 0
) {
name
age
email
}
}
# ============================================
# DQL (Dgraph Query Language) 예제
# ============================================
# 기본 쿼리
{
people(func: type(Person), orderasc: name, first: 10) {
uid
name
age
email
}
}
# 그래프 순회 - 친구의 친구 찾기
{
alice(func: eq(name, "Alice")) {
name
friends {
name
friends {
name
}
}
}
}
# 재귀 쿼리 - N단계 관계 탐색
{
connections(func: eq(name, "Alice")) @recurse(depth: 3) {
name
friends
}
}
# 필터와 집계
{
stats(func: type(Person)) @filter(ge(age, 25)) {
count(uid)
avg_age: avg(age)
min_age: min(age)
max_age: max(age)
}
}
# 전문 검색
{
search(func: alloftext(content, "machine learning AI")) {
title
content
author {
name
}
}
}
# 지리공간 쿼리
{
nearby(func: near(location, [37.5665, 126.9780], 5000)) {
name
location
}
}
# ============================================
# 뮤테이션 예제
# ============================================
# GraphQL 뮤테이션
mutation {
addPerson(input: [{
name: "Eve"
age: 30
email: "eve@example.com"
friends: { name: "Alice" }
}]) {
person {
id
name
}
}
}
# DQL 뮤테이션 (RDF 형식)
{
set {
_:eve "Person" .
_:eve "Eve" .
_:eve "30"^^ .
_:eve "eve@example.com" .
}
}
"I recommend Dgraph for the social features. Once you define just the GraphQL schema, the API is generated automatically, so development speed goes up. Graph queries like friend recommendations can also be done with recursive traversal in DQL, which is advantageous for complex relationship analysis."
"Dgraph is designed as a distributed system from the start, so scaling out comes naturally. You just add Alpha nodes, and sharding and replication are handled automatically. It can also handle graphs with more than 1 billion nodes. However, there is operational complexity, so consider a cloud managed option as well."
"Neo4j's strengths are the Cypher query language and a mature ecosystem, while Dgraph's strengths are native GraphQL and horizontal scaling. If you're already using GraphQL on the frontend, Dgraph is easier to integrate, and if analytics is the focus, Neo4j may be more familiar."
DQL is similar to GraphQL but is a separate syntax. Consider the cost of having the entire team learn a new query language.
You have to manage multiple components such as Zero, Alpha, and Ratel. The overhead can be large for small projects.
Because graph data is cached in memory, large datasets require sufficient RAM. At least 16GB per node is recommended.
Set indexes appropriately (@index), and use @reverse to take advantage of reverse edges. Paginate queries with first/offset, and set a depth limit for deep recursion.