🗄️ Databases

ArangoDB

Multi-Model Database

An open-source multi-model database that supports document, graph, and key-value models in a single engine. All data models can be queried together using AQL (ArangoDB Query Language).

📖 Detailed Explanation

ArangoDB is a native multi-model database that originated in Germany in 2011. A single engine handles a document store (replacing MongoDB), a graph database (replacing Neo4j), and a key-value store. You can manage diverse data structures in one system without having to operate multiple databases.

AQL (ArangoDB Query Language) is a declarative query language similar to SQL that handles document filtering, graph traversal, and joins in a single query. Its FOR...FILTER...RETURN pattern is intuitive, and it provides the GRAPH keyword specialized for graph exploration.

Foxx Microservices is a feature that runs microservices directly inside ArangoDB using JavaScript. Without a separate application server, you can integrate the database and business logic, which reduces latency and simplifies the architecture.

It supports horizontal scaling and distributed graph processing through clustering and SmartGraphs. It automatically shards data, and with smart sharding that minimizes network hops during graph traversal, it ensures large-scale graph query performance.

It is suitable for use cases that mix various data models, such as recommendation systems, fraud detection, knowledge graphs, and IoT data processing.

💻 Code Example

# ArangoDB Python 드라이버 (python-arango)
from arango import ArangoClient

# 클라이언트 연결
client = ArangoClient(hosts='http://localhost:8529')

# 시스템 DB 연결 후 사용자 DB 생성
sys_db = client.db('_system', username='root', password='password')

# 새 데이터베이스 생성 (없으면)
if not sys_db.has_database('myapp'):
    sys_db.create_database('myapp')

# 애플리케이션 DB 연결
db = client.db('myapp', username='root', password='password')

# 컬렉션 생성 (문서 저장소)
if not db.has_collection('users'):
    users = db.create_collection('users')
else:
    users = db.collection('users')

# 엣지 컬렉션 생성 (그래프 관계)
if not db.has_collection('follows'):
    follows = db.create_collection('follows', edge=True)
else:
    follows = db.collection('follows')

# 문서 삽입
user1 = users.insert({'_key': 'alice', 'name': 'Alice', 'age': 28})
user2 = users.insert({'_key': 'bob', 'name': 'Bob', 'age': 32})
user3 = users.insert({'_key': 'charlie', 'name': 'Charlie', 'age': 25})

# 엣지 삽입 (관계 생성)
follows.insert({'_from': 'users/alice', '_to': 'users/bob'})
follows.insert({'_from': 'users/bob', '_to': 'users/charlie'})
follows.insert({'_from': 'users/alice', '_to': 'users/charlie'})

# 그래프 생성
if not db.has_graph('social'):
    graph = db.create_graph('social')
    graph.create_edge_definition(
        edge_collection='follows',
        from_vertex_collections=['users'],
        to_vertex_collections=['users']
    )
else:
    graph = db.graph('social')

# AQL 쿼리 실행 - 2단계 팔로우 관계 탐색
cursor = db.aql.execute('''
    FOR user IN users
        FILTER user._key == 'alice'
        FOR friend, edge, path IN 1..2 OUTBOUND user follows
            RETURN DISTINCT {
                name: friend.name,
                depth: LENGTH(path.edges)
            }
''')

print("Alice의 팔로우 네트워크:")
for doc in cursor:
    print(f"  {doc['name']} (깊이: {doc['depth']})")

# 문서 + 그래프 조합 쿼리
cursor = db.aql.execute('''
    FOR user IN users
        FILTER user.age >= 25
        LET follower_count = LENGTH(
            FOR f IN follows FILTER f._to == user._id RETURN 1
        )
        RETURN {
            name: user.name,
            age: user.age,
            followers: follower_count
        }
''')

print("\n팔로워 통계:")
for doc in cursor:
    print(f"  {doc['name']}: {doc['followers']}명")
// ArangoDB Node.js 드라이버 (arangojs)
const { Database, aql } = require('arangojs');

async function main() {
    // 데이터베이스 연결
    const db = new Database({
        url: 'http://localhost:8529',
        databaseName: 'myapp',
        auth: { username: 'root', password: 'password' }
    });

    // 컬렉션 접근
    const products = db.collection('products');
    const categories = db.collection('categories');
    const belongs_to = db.collection('belongs_to'); // 엣지

    // 문서 삽입 (upsert 패턴)
    await db.query(aql`
        UPSERT { _key: "laptop-001" }
        INSERT {
            _key: "laptop-001",
            name: "MacBook Pro",
            price: 2499,
            specs: { cpu: "M3", ram: "16GB", storage: "512GB" }
        }
        UPDATE { price: 2499 }
        IN products
    `);

    // 중첩 문서 쿼리
    const cursor = await db.query(aql`
        FOR p IN products
            FILTER p.specs.ram == "16GB"
            SORT p.price DESC
            RETURN { name: p.name, price: p.price }
    `);

    console.log('16GB RAM 제품:');
    for await (const product of cursor) {
        console.log(`  ${product.name}: $${product.price}`);
    }

    // 그래프 순회 - 카테고리별 제품 탐색
    const categoryProducts = await db.query(aql`
        FOR cat IN categories
            FILTER cat.name == "Electronics"
            FOR product IN 1..1 INBOUND cat belongs_to
                COLLECT category = cat.name INTO products = product
                RETURN {
                    category: category,
                    products: products[*].name,
                    total: LENGTH(products)
                }
    `);

    console.log('\n카테고리별 제품:');
    for await (const result of categoryProducts) {
        console.log(`  ${result.category}: ${result.total}개`);
    }

    // 트랜잭션 처리
    const trx = await db.beginTransaction({
        read: ['products'],
        write: ['orders', 'products']
    });

    try {
        await trx.step(() => db.query(aql`
            INSERT {
                product_id: "laptop-001",
                quantity: 1,
                total: 2499,
                created_at: DATE_NOW()
            } INTO orders
        `));

        await trx.step(() => db.query(aql`
            UPDATE { _key: "laptop-001" }
            WITH { stock: OLD.stock - 1 }
            IN products
        `));

        await trx.commit();
        console.log('\n주문 완료!');
    } catch (err) {
        await trx.abort();
        console.error('트랜잭션 실패:', err.message);
    }
}

main().catch(console.error);
// ============================================
// AQL 기본 쿼리
// ============================================

// 문서 조회 (기본)
FOR user IN users
    FILTER user.age >= 25 AND user.status == "active"
    SORT user.created_at DESC
    LIMIT 10
    RETURN user

// 문서 삽입
INSERT {
    name: "신규 사용자",
    email: "new@example.com",
    created_at: DATE_NOW()
} INTO users
RETURN NEW

// 문서 업데이트
UPDATE "user123" WITH {
    last_login: DATE_NOW(),
    login_count: OLD.login_count + 1
} IN users
RETURN NEW


// ============================================
// 그래프 순회 (Graph Traversal)
// ============================================

// 1단계 팔로우 관계
FOR user IN users
    FILTER user._key == "alice"
    FOR friend IN 1..1 OUTBOUND user follows
        RETURN friend.name

// 최대 3단계까지 관계 탐색
FOR user IN users
    FILTER user._key == "alice"
    FOR connected, edge, path IN 1..3 ANY user follows
        OPTIONS { bfs: true, uniqueVertices: 'global' }
        RETURN {
            person: connected.name,
            depth: LENGTH(path.edges),
            via: path.vertices[*].name
        }

// 최단 경로 찾기
FOR v, e IN OUTBOUND SHORTEST_PATH
    'users/alice' TO 'users/charlie'
    GRAPH 'social'
    RETURN { vertex: v.name, edge: e }


// ============================================
// 조인과 집계
// ============================================

// 컬렉션 조인
FOR order IN orders
    FOR user IN users
        FILTER order.user_id == user._key
        RETURN {
            order_id: order._key,
            customer: user.name,
            total: order.amount
        }

// 그룹화 및 집계
FOR order IN orders
    COLLECT user_id = order.user_id
    AGGREGATE total = SUM(order.amount), count = LENGTH(1)
    SORT total DESC
    RETURN {
        user: user_id,
        order_count: count,
        total_spent: total
    }


// ============================================
// 전문 검색 (Full-Text Search)
// ============================================

// Analyzer 뷰 사용
FOR doc IN product_search
    SEARCH ANALYZER(
        doc.description IN TOKENS("wireless bluetooth headphones", "text_en"),
        "text_en"
    )
    SORT BM25(doc) DESC
    LIMIT 10
    RETURN { name: doc.name, score: BM25(doc) }

🗣️ Say It Like This in Practice

💬 In an architecture design meeting
"For a recommendation system, we need to store user profiles as documents and relationships as a graph. Rather than running both MongoDB and Neo4j, consolidating into a single ArangoDB can greatly reduce operational complexity. With AQL alone, you can handle document filtering and graph traversal at the same time."
💬 In a Tech Stack Selection Discussion
"The core of a fraud detection system is analyzing transaction patterns. With ArangoDB's SmartGraphs, graph traversal performs well even in a distributed environment. Related nodes are placed on the same shard to minimize network hops."
💬 In a migration planning discussion
"When migrating from MongoDB to ArangoDB, you can bring over the document structure almost as it is. Import the JSON data with the arangoimport tool, and just convert the queries from the Aggregation Pipeline to AQL. For graph relationships, you only need to additionally design edge collections."

⚠️ Cautions & Best Practices

❌
Community Size Limitations

Its community and ecosystem are smaller than those of MongoDB and Neo4j. When solving specific problems, you may have to rely on the official documentation and GitHub issues.

❌
Memory for Large-Scale Graph Traversal

Complex graph queries use a lot of memory. For deep traversals (depth > 3), use OPTIONS { bfs: true } and LIMIT appropriately.

❌
Foxx Microservice Constraints

Foxx is convenient, but it has the constraints of the V8 JavaScript runtime. If you need CPU-intensive work or many external libraries, consider a separate server.

✅
Best Practices

When designing graphs, clearly separate edge collections, and place related data on the same shard with SmartGraphs. Optimize performance with index design and query EXPLAIN.

🔗 Related Terms

📚 Learn More