Skip to content

REST API 使用

REST API 基础

1. API 端点

Neo4j 提供了 REST API 用于与数据库进行交互,主要端点包括:

  • 事务 API/db/{databaseName}/tx - 用于执行事务
  • 查询 API/db/{databaseName}/tx/commit - 用于执行单个查询
  • 节点 API/db/{databaseName}/nodes - 用于管理节点
  • 关系 API/db/{databaseName}/relationships - 用于管理关系
  • 属性 API/db/{databaseName}/nodes/{nodeId}/properties - 用于管理属性

2. 请求格式

  • HTTP 方法:GET, POST, PUT, DELETE
  • Content-Typeapplication/json
  • 响应格式:JSON

3. 基本认证

Neo4j REST API 使用基本认证(Basic Authentication):

Authorization: Basic <base64-encoded username:password>

API 认证

1. 基本认证

bash
# 使用 curl 进行基本认证
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/tx/commit \
  -H "Content-Type: application/json" \
  -d '{"statements":[{"statement":"MATCH (n) RETURN count(n)"}]}'

2. 令牌认证

Neo4j 4.0+ 支持基于令牌的认证:

bash
# 获取令牌
curl -X POST http://localhost:7474/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'grant_type=password&username=neo4j&password=password'

# 使用令牌
curl -X POST http://localhost:7474/db/neo4j/tx/commit \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"statements":[{"statement":"MATCH (n) RETURN count(n)"}]}'

常见 API 操作

1. 执行查询

bash
# 执行单个查询
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/tx/commit \
  -H "Content-Type: application/json" \
  -d '{
    "statements": [{
      "statement": "MATCH (p:Person) RETURN p.name AS name, p.age AS age",
      "parameters": {},
      "resultDataContents": ["row", "graph"]
    }]
  }'

2. 执行事务

bash
# 开始事务
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/tx \
  -H "Content-Type: application/json"

# 执行操作
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/tx/{txId} \
  -H "Content-Type: application/json" \
  -d '{
    "statements": [{
      "statement": "CREATE (p:Person {name: $name, age: $age})",
      "parameters": {"name": "John", "age": 30}
    }]
  }'

# 提交事务
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/tx/{txId}/commit

# 回滚事务
curl -u neo4j:password -X DELETE http://localhost:7474/db/neo4j/tx/{txId}

3. 管理节点

bash
# 创建节点
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/nodes \
  -H "Content-Type: application/json" \
  -d '{"labels": ["Person"], "properties": {"name": "John", "age": 30}}'

# 获取节点
curl -u neo4j:password -X GET http://localhost:7474/db/neo4j/nodes/{nodeId}

# 更新节点
curl -u neo4j:password -X PUT http://localhost:7474/db/neo4j/nodes/{nodeId}/properties \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "age": 31}'

# 删除节点
curl -u neo4j:password -X DELETE http://localhost:7474/db/neo4j/nodes/{nodeId}

4. 管理关系

bash
# 创建关系
curl -u neo4j:password -X POST http://localhost:7474/db/neo4j/relationships \
  -H "Content-Type: application/json" \
  -d '{
    "start": "/db/neo4j/nodes/{startNodeId}",
    "end": "/db/neo4j/nodes/{endNodeId}",
    "type": "FRIENDS_WITH",
    "properties": {"since": 2010}
  }'

# 获取关系
curl -u neo4j:password -X GET http://localhost:7474/db/neo4j/relationships/{relationshipId}

# 更新关系
curl -u neo4j:password -X PUT http://localhost:7474/db/neo4j/relationships/{relationshipId}/properties \
  -H "Content-Type: application/json" \
  -d '{"since": 2009, "strength": 5}'

# 删除关系
curl -u neo4j:password -X DELETE http://localhost:7474/db/neo4j/relationships/{relationshipId}

API 性能优化

1. 批量操作

  • 批量执行查询:在单个请求中执行多个查询
  • 批量创建节点:一次性创建多个节点
  • 批量创建关系:一次性创建多个关系

2. 参数化查询

  • 使用参数:避免字符串拼接
  • 预编译语句:提高查询性能
  • 缓存查询计划:减少查询解析时间

3. 分页与限制

  • 使用 LIMIT:限制返回结果数量
  • 使用 SKIP:实现分页
  • 使用 COUNT:避免返回过多数据

4. 响应格式优化

  • 选择合适的结果格式:根据需要选择 row 或 graph 格式
  • 减少不必要的字段:只返回需要的字段
  • 使用压缩:启用 HTTP 压缩

5. 连接管理

  • 使用连接池:复用 HTTP 连接
  • 减少请求次数:合并多个操作
  • 使用持久连接:减少连接建立开销

示例:使用 Python 调用 REST API

python
import requests
import json

# 认证信息
auth = ('neo4j', 'password')
url = 'http://localhost:7474/db/neo4j/tx/commit'

# 执行查询
def run_query(query, params=None):
    payload = {
        'statements': [{
            'statement': query,
            'parameters': params or {}
        }]
    }
    response = requests.post(url, auth=auth, json=payload)
    return response.json()

# 创建节点
def create_person(name, age):
    query = "CREATE (p:Person {name: $name, age: $age}) RETURN p"
    return run_query(query, {'name': name, 'age': age})

# 查询节点
def get_persons():
    query = "MATCH (p:Person) RETURN p.name AS name, p.age AS age"
    result = run_query(query)
    return result['results'][0]['data']

# 示例调用
if __name__ == '__main__':
    # 创建人员
    create_person('John', 30)
    create_person('Alice', 28)
    
    # 查询人员
    persons = get_persons()
    for person in persons:
        print(person['row'])

示例:使用 JavaScript 调用 REST API

javascript
const axios = require('axios');

// 认证信息
const auth = {
    username: 'neo4j',
    password: 'password'
};
const url = 'http://localhost:7474/db/neo4j/tx/commit';

// 执行查询
async function runQuery(query, params = {}) {
    const payload = {
        statements: [{
            statement: query,
            parameters: params
        }]
    };
    
    const response = await axios.post(url, payload, {
        auth: auth
    });
    
    return response.data;
}

// 创建节点
async function createPerson(name, age) {
    const query = "CREATE (p:Person {name: $name, age: $age}) RETURN p";
    return await runQuery(query, {name, age});
}

// 查询节点
async function getPersons() {
    const query = "MATCH (p:Person) RETURN p.name AS name, p.age AS age";
    const result = await runQuery(query);
    return result.results[0].data;
}

// 示例调用
(async () => {
    // 创建人员
    await createPerson('John', 30);
    await createPerson('Alice', 28);
    
    // 查询人员
    const persons = await getPersons();
    persons.forEach(person => {
        console.log(person.row);
    });
})();

小结

REST API 是与 Neo4j 进行交互的重要方式,通过 REST API,可以在任何支持 HTTP 的语言中与 Neo4j 进行通信。本文介绍了 REST API 的基本用法、认证方式、常见操作和性能优化策略。在实际应用中,需要根据具体的需求和技术栈,选择合适的 API 调用方式,并进行必要的性能优化。

在接下来的章节中,我们将介绍可视化工具,这是探索和分析图数据的重要工具。