选择python-arango库的核心优势在于其官方支持、全面的api覆盖、异步操作能力、良好的类型提示与异常处理机制以及内置连接池管理;2. 它能通过直观的pythonic接口实现文档的增删改查、aql参数化查询、批量操作和索引管理,显著提升开发效率与运行性能;3. 在处理图数据时,该库提供图对象抽象,支持顶点和边集合的便捷管理,可通过图结构定义关系并执行高效图遍历操作,是python与arangodb交互的成熟可靠方案。
Python操作ArangoDB,最直接且推荐的方式是利用其官方支持的
python-arango
要用
python-arango
pip install python-arango
连接到数据库是第一步,通常需要指定主机、端口、数据库名和认证信息。
立即学习“Python免费学习笔记(深入)”;
from arango import ArangoClient from arango.exceptions import DocumentInsertError, ArangoClientError # 初始化客户端 try: client = ArangoClient(hosts="http://localhost:8529") # 连接到数据库(需要用户名和密码) # 如果是_system数据库,直接db = client.db("_system", username="root", password="your_password") # 如果是其他数据库,需要先确保该数据库存在并有权限 db = client.db("my_new_database", username="root", password="your_password") # 确保数据库存在,如果不存在则创建(可选,需要_system数据库的root权限) # if not db.verify(): # print("Database 'my_new_database' does not exist or credentials are wrong.") # client.create_database("my_new_database") # 这需要在_system数据库的root权限下执行 # db = client.db("my_new_database", username="root", password="your_password") # print("Database 'my_new_database' created.") # 获取一个集合对象 collection = db.collection("my_documents") # 如果集合不存在,创建它 if not collection.exists(): collection.create() print("Collection 'my_documents' created.") # 插入文档 new_doc = {"name": "Alice", "age": 30, "city": "New York"} result = collection.insert(new_doc) print(f"Inserted document: {result['_key']}") # 读取文档 fetched_doc = collection.get(result['_key']) print(f"Fetched document: {fetched_doc}") # 更新文档 updated_doc_data = {"age": 31, "occupation": "Engineer"} updated_doc = collection.update(fetched_doc, updated_doc_data) print(f"Updated document: {updated_doc}") # 删除文档 # collection.delete(updated_doc) # print(f"Deleted document: {updated_doc['_key']}") # 执行AQL查询 cursor = db.aql.execute( "FOR d IN my_documents FILTER d.age > @min_age RETURN d", bind_vars={"min_age": 30} ) print("Documents with age > 30:") for doc in cursor: print(doc) except ArangoClientError as e: print(f"ArangoDB Client Error: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")
python-arango
我个人觉得,选择
python-arango
它的优势体现在几个方面:
python-arango
python-arango
AsyncArangoClient
asyncio
python-arango
我记得有一次,我需要快速搭建一个原型,涉及大量AQL查询和图遍历。
python-arango
在实际项目中,尤其数据量上来后,效率是个大问题。我总结了一些经验:
批量操作: 单个文档的插入、更新、删除,在数据量小的时候没问题,但如果一次性要处理成百上千甚至更多,逐个操作的网络开销会非常大。
python-arango
insert_many
update_many
# 批量插入示例 docs_to_insert = [ {"name": "Bob", "age": 25, "city": "London"}, {"name": "Charlie", "age": 35, "city": "Paris"} ] results = collection.insert_many(docs_to_insert) print(f"Inserted {len(results)} documents in bulk.")
这能显著减少网络往返次数,提升吞吐量。
AQL参数化查询: 永远不要直接拼接SQL(或AQL)字符串!这不仅是安全问题(SQL注入),更是性能问题。
python-arango
db.aql.execute
bind_vars
# 避免:f"FOR d IN my_documents FILTER d.name == '{user_input_name}' RETURN d" # 推荐: user_input_name = "Alice" cursor = db.aql.execute( "FOR d IN my_documents FILTER d.name == @target_name RETURN d", bind_vars={"target_name": user_input_name} ) for doc in cursor: print(doc)
这样做,ArangoDB可以缓存查询计划,每次执行时只需替换参数,效率更高。
索引优化: AQL查询慢,十有八九是索引没建好。在使用
python-arango
python-arango
# 创建哈希索引 if not collection.has_index(["name", "city"]): collection.add_hash_index(["name", "city"], unique=False) print("Hash index on 'name' and 'city' created.")
我之前就遇到过一个查询,跑了十几秒,加上一个复合索引后,瞬间降到几十毫秒,效果立竿见影。
游标管理: 对于返回大量结果的AQL查询,
db.aql.execute
python-arango
ArangoDB最吸引人的特性之一就是它的多模型能力,尤其是图数据。
python-arango
图对象的抽象: 你可以很方便地获取一个图对象,然后通过它来管理图中的顶点集合和边集合。
# 获取或创建图 graph = db.graph("my_social_graph") if not graph.exists(): # 创建图时可以指定边定义,这里简化 graph.create() print("Graph 'my_social_graph' created.") # 获取顶点集合和边集合 users_collection = graph.vertex_collection("users") follows_collection = graph.edge_collection("follows") # 如果集合不存在,创建它们 if not users_collection.exists(): users_collection.create() if not follows_collection.exists(): # 边集合需要定义来源和目标顶点集合 graph.add_edge_definition( edge_collection_name="follows", from_vertex_collections=["users"], to_vertex_collections
以上就是Python如何操作ArangoDB?python-arango的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号