### Set Up Development Environment Source: https://github.com/arangodb/python-arango/blob/main/CONTRIBUTING.md Installs development dependencies and sets up git pre-commit hooks. Ensure you are in your repository fork and have an active virtual environment. ```shell cd ~/your/repository/fork # Activate venv if you have one (recommended) pip install -e .[dev] # Install dev dependencies (e.g. black, mypy, pre-commit) pre-commit install # Install git pre-commit hooks ``` -------------------------------- ### Install and Run Pytest for Integration Tests Source: https://github.com/arangodb/python-arango/blob/main/docs/contributing.md Install pytest and run the integration test suite against an ArangoDB instance. Ensure you provide your host, port, and root password. ```bash ~$ pip install pytest ~$ git clone https://github.com/arangodb/python-arango.git ~$ cd python-arango ~$ pytest --cluster --host=127.0.0.1 --port=8529 --password=passwd ``` -------------------------------- ### Start ArangoDB Instance Locally Source: https://github.com/arangodb/python-arango/blob/main/CONTRIBUTING.md Launches an ArangoDB instance using the provided starter script. Docker is a prerequisite for this command. ```shell ./starter.sh # Requires docker ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/arangodb/python-arango/blob/main/docs/contributing.md Install Sphinx and the Read the Docs theme, then build the HTML documentation locally. Open the generated index.html file in a browser to view the documentation. ```bash ~$ pip install sphinx sphinx_rtd_theme ~$ git clone https://github.com/arangodb/python-arango.git ~$ cd python-arango ~$ python -m sphinx -b html -W docs docs/_build/ # Open build/index.html in a browser ``` -------------------------------- ### Install and Run Flake8 for PEP8 Compliance Source: https://github.com/arangodb/python-arango/blob/main/docs/contributing.md Install the flake8 linter and run it on the cloned repository to check for PEP8 compliance. This helps maintain consistent code style. ```bash ~$ pip install flake8 ~$ git clone https://github.com/arangodb/python-arango.git ~$ cd python-arango ~$ flake8 ``` -------------------------------- ### Install python-arango Source: https://github.com/arangodb/python-arango/blob/main/docs/index.md Install the python-arango package using pip. It is recommended to upgrade to the latest version. ```bash ~$ pip install python-arango --upgrade ``` -------------------------------- ### Install Python-Arango Source: https://github.com/arangodb/python-arango/blob/main/README.md Install the python-arango package using pip. Ensure you have Python 3.9+ and ArangoDB 3.11+. ```shell pip install python-arango --upgrade ``` -------------------------------- ### Server Administration Source: https://context7.com/arangodb/python-arango/llms.txt Provides examples for querying server status, metrics, logs, managing JWT secrets, and performing administrative tasks like compacting databases. ```APIDOC ## Server Administration ### Description Query server status, metrics, logs, and manage JWT secrets. ### Method ```python from arango import ArangoClient client = ArangoClient() db = client.db("_system", username="root", password="passwd") # Server info print(db.version()) # '3.11.x' print(db.role()) # 'SINGLE' | 'COORDINATOR' | ... print(db.mode()) # 'default' | 'readonly' print(db.engine()) # {'name': 'rocksdb', ...} print(db.status()) # detailed server status dict # Prometheus metrics metrics_text = db.metrics() print(metrics_text[:200]) # '# HELP arangodb_...' # Log levels print(db.log_levels()) db.set_log_levels(agency="DEBUG", collector="INFO") db.reset_log_levels() # Read log entries entries = db.read_log_entries(level="warning", size=50, sort="desc") print(entries) # Compact all databases (use with care) db.compact(change_level=False, compact_bottom_most_level=True) # Server statistics stats = db.statistics() print(stats["system"]["virtual_size"]) # Reload routing table db.reload_routing() ``` ``` -------------------------------- ### Configure and Control Replication Applier Source: https://github.com/arangodb/python-arango/blob/main/docs/replication.md Update, start, and stop the replication applier. Ensure correct endpoint, database credentials, and desired configuration parameters are provided. ```python # Update the replication applier configuration. result = replication.set_applier_config( endpoint='http://127.0.0.1:8529', database='test', username='root', password='passwd', max_connect_retries=120, connect_timeout=15, request_timeout=615, chunk_size=0, auto_start=True, adaptive_polling=False, include_system=True, auto_resync=True, auto_resync_retries=3, initial_sync_max_wait_time=405, connection_retry_wait_time=25, idle_min_wait_time=2, idle_max_wait_time=3, require_from_present=False, verbose=True, restrict_type='include', restrict_collections=['students'] ) # Get the replication applier state. replication.applier_state() # Start the replication applier. replication.start_applier() # Stop the replication applier. replication.stop_applier() ``` -------------------------------- ### Create Pregel Job Source: https://github.com/arangodb/python-arango/blob/main/docs/pregel.md Starts a new Pregel job on a specified graph with a given algorithm and configuration. ```APIDOC ## POST /_api/control_pregel/create_job ### Description Starts a new Pregel job. ### Method POST ### Endpoint /_api/control_pregel/create_job ### Parameters #### Query Parameters - **graph** (string) - Required - The name of the graph to run the Pregel job on. - **algorithm** (string) - Required - The Pregel algorithm to use (e.g., 'pagerank'). - **store** (boolean) - Optional - Whether to store the results in a collection. - **max_gss** (integer) - Optional - The maximum number of global supersteps. - **thread_count** (integer) - Optional - The number of threads to use for the computation. - **async_mode** (boolean) - Optional - Whether to run the job in asynchronous mode. - **result_field** (string) - Optional - The field in the result document to store the computed values. #### Request Body - **algorithm_params** (object) - Optional - Parameters specific to the chosen algorithm. - **threshold** (float) - Example parameter for an algorithm. ### Request Example ```json { "graph": "school", "algorithm": "pagerank", "store": false, "max_gss": 100, "thread_count": 1, "async_mode": false, "result_field": "result", "algorithm_params": { "threshold": 0.000001 } } ``` ### Response #### Success Response (200) - **job_id** (integer) - The ID of the created Pregel job. #### Response Example ```json { "job_id": 12345 } ``` ``` -------------------------------- ### Enable HTTP Request/Response Logging Source: https://github.com/arangodb/python-arango/blob/main/docs/logging.md Configure the logging level for the 'requests' library and its dependencies to DEBUG to see full HTTP details. This setup is necessary for debugging network-level issues. ```python import requests import logging try: # For Python 3 from http.client import HTTPConnection except ImportError: # For Python 2 from httplib import HTTPConnection HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True ``` -------------------------------- ### Replication Applier Control Source: https://github.com/arangodb/python-arango/blob/main/docs/replication.md Control the start and stop actions for the replication applier. ```APIDOC ## start_applier ### Description Starts the replication applier. ### Method `replication.start_applier()` ## stop_applier ### Description Stops the replication applier. ### Method `replication.stop_applier()` ``` -------------------------------- ### Get Document Source: https://context7.com/arangodb/python-arango/llms.txt Retrieves a single document from a collection by its key. ```python doc = students.get("S001") print(doc) ``` -------------------------------- ### Get Server Information Source: https://github.com/arangodb/python-arango/blob/main/docs/cluster.md Retrieves various details about the current server and the cluster. Includes server ID, role, health, server count, engine, version, and statistics. ```python # Get this server's ID. cluster.server_id() # Get this server's role. cluster.server_role() # Get the cluster health. cluster.health() # Get cluster server details. cluster.server_count() server_id = cluster.server_id() cluster.server_engine(server_id) cluster.server_version(server_id) cluster.server_statistics(server_id) cluster.server_maintenance_mode(server_id) ``` -------------------------------- ### Run Pytest with Coverage Report Source: https://github.com/arangodb/python-arango/blob/main/docs/contributing.md Install coverage tools and run the integration tests with coverage reporting enabled. This helps identify areas of the code not covered by tests. ```bash ~$ pip install coverage pytest pytest-cov ~$ git clone https://github.com/arangodb/python-arango.git ~$ cd python-arango ~$ pytest --cluster --host=127.0.0.1 --port=8529 --password=passwd --cov=kq ``` -------------------------------- ### Download Backup Source: https://github.com/arangodb/python-arango/blob/main/docs/backup.md Downloads a backup from a specified remote repository. Supports getting download status and aborting an ongoing download. ```APIDOC ## download ### Description Downloads a backup from a remote repository. ### Method `backup.download()` ### Parameters - **backup_id** (string) - Required - The ID of the backup to download. - **repository** (string) - Required - The remote repository to download from (e.g., 'local://tmp/backups'). - **config** (object) - Required - Configuration for the repository (e.g., `{'local': {'type': 'local'}}`). - **download_id** (string) - Optional - If provided, this indicates an operation on an existing download. Used for getting status or aborting. - **abort** (boolean) - Optional - If true and `download_id` is provided, aborts the ongoing download. ### Response #### Success Response (200) - **download_id** (string) - The ID of the download operation (when initiating a download). - (No specific response body documented for status/abort, implies success if no error). ### Request Example ```python # Download a backup result = backup.download( backup_id=backup_id, repository='local://tmp/backups', config={'local': {'type': 'local'}} ) download_id = result['download_id'] # Get status of an download. backup.download(download_id=download_id) # Abort an download. backup.download(download_id=download_id, abort=True) ``` ``` -------------------------------- ### Control Server Overload Source: https://context7.com/arangodb/python-arango/llms.txt Gracefully handle server overload by capping the maximum server-side queue time for AQL queries. Use `begin_controlled_execution` to start a session with a limit, and `adjust_max_queue_time` to modify or disable it. ```python from arango import ArangoClient from arango.exceptions import ArangoServerError client = ArangoClient() db = client.db("test", username="root", password="passwd") # Begin a controlled session: reject if server queues > 2 s controlled = db.begin_controlled_execution(max_queue_time_seconds=2.0) try: result = controlled.aql.execute("FOR s IN students RETURN s") docs = list(result) except ArangoServerError as err: print(f"Server overloaded, queue time exceeded: {err}") # Inspect queue time for the last request print(controlled.last_queue_time) # e.g. 0.012 # Dynamically adjust the limit controlled.adjust_max_queue_time(5.0) # Disable the limit controlled.adjust_max_queue_time(None) ``` -------------------------------- ### Outbound Graph Traversal (BFS) Source: https://github.com/arangodb/python-arango/blob/main/README.md Execute an AQL query to traverse a graph in an outbound direction using breadth-first search. Specify the traversal depth, starting vertex, graph name, and traversal options. The result includes vertices, edges, and paths. ```python query = """ FOR v, e, p IN 1..3 OUTBOUND 'students/01' GRAPH 'school' OPTIONS { order: 'bfs', uniqueVertices: 'global' } RETURN {vertex: v, edge: e, path: p} """ cursor = db.aql.execute(query) ``` -------------------------------- ### Define Custom HTTP Client Source: https://github.com/arangodb/python-arango/blob/main/docs/http.md Implement a custom HTTP client by inheriting from `arango.http.HTTPClient` and overriding `create_session` and `send_request`. This example shows how to add custom headers, disable SSL verification, and implement retry logic. ```python from arango.http import HTTPClient from arango.response import Response import requests class CustomHTTPClient(HTTPClient): def create_session(self, host: str) -> requests.Session: session = requests.Session() session.headers.update({'x-my-header': 'my-value'}) session.verify = False return session def send_request(self, method: str, url: str, **kwargs) -> Response: session = self.get_session(url) try: response = session.request(method, url, **kwargs) return Response(response.status_code, response.headers, response.text) except requests.exceptions.RequestException as e: # Handle retries or other error logic here raise e ``` -------------------------------- ### Execute ACID Stream Transactions Source: https://context7.com/arangodb/python-arango/llms.txt Shows how to perform operations across multiple collections within a single ACID transaction using the Python driver. Includes starting a transaction, performing read/write operations, committing, aborting, and resuming transactions. ```python from arango import ArangoClient from arango.exceptions import TransactionCommitError client = ArangoClient() db = client.db("test", username="root", password="passwd") # Begin a stream transaction declaring read/write collections txn = db.begin_transaction( read=["accounts"], write=["accounts", "audit_log"], lock_timeout=5, max_size=128 * 1024, # 128 KB ) try: acct_col = txn.collection("accounts") log_col = txn.collection("audit_log") # Read and modify inside the transaction acct = acct_col.get("ACC001") acct["balance"] -= 100 acct_col.replace(acct) log_col.insert({"action": "debit", "amount": 100, "account": "ACC001"}) # Commit txn.commit_transaction() except TransactionCommitError as err: txn.abort_transaction() raise # Fetch and resume an existing transaction by ID existing_txn = db.fetch_transaction("") print(existing_txn.transaction_status()) ``` ```javascript function (params) { const db = require('@arangodb').db; db.counters.update(params.key, { value: params.val }); return db.counters.document(params.key); } ``` ```python # JS transaction (single-request, legacy) result = db.execute_transaction( command=""" function (params) { const db = require('@arangodb').db; db.counters.update(params.key, { value: params.val }); return db.counters.document(params.key); } """, params={"key": "hits", "val": 99}, write=["counters"], sync=True, ) print(result) ``` -------------------------------- ### Get Last WAL Tick Source: https://github.com/arangodb/python-arango/blob/main/docs/wal.md Get the last available tick value in the WAL. ```APIDOC ## Get Last WAL Tick ### Description Get the last available tick value in the WAL. ### Method `wal.last_tick()` ### Parameters None ### Request Example ```python wal.last_tick() ``` ### Response #### Success Response (200) Returns the last available tick value. #### Response Example ```json "1000" ``` ``` -------------------------------- ### Get WAL Tick Ranges Source: https://github.com/arangodb/python-arango/blob/main/docs/wal.md Get the available ranges of tick values in the WAL. ```APIDOC ## Get WAL Tick Ranges ### Description Get the available ranges of tick values in the WAL. ### Method `wal.tick_ranges()` ### Parameters None ### Request Example ```python wal.tick_ranges() ``` ### Response #### Success Response (200) Returns a list of tick value ranges. #### Response Example ```json [ { "start": "1", "end": "1000" } ] ``` ``` -------------------------------- ### Get Recent WAL Operations Source: https://github.com/arangodb/python-arango/blob/main/docs/wal.md Get recent WAL operations. This is useful for tailing the WAL. ```APIDOC ## Get Recent WAL Operations ### Description Get recent WAL operations. This is useful for tailing the WAL. ### Method `wal.tail()` ### Parameters None ### Request Example ```python wal.tail() ``` ### Response #### Success Response (200) Returns a list of recent WAL operations. #### Response Example ```json [ { "tick": "999", "type": "insert", "data": { "_key": "doc1", "value": "test" } } ] ``` ``` -------------------------------- ### Create Graph, Insert Data, and Perform BFS Traversal Source: https://context7.com/arangodb/python-arango/llms.txt Demonstrates creating vertex and edge collections, inserting data, and performing a Breadth-First Search (BFS) traversal using AQL. It also shows how to check for graph existence and delete a graph. ```python students = graph.create_vertex_collection("students") courses = graph.create_vertex_collection("courses") edges = graph.create_edge_definition( edge_collection="enrolled_in", from_vertex_collections=["students"], to_vertex_collections=["courses"], ) # Insert vertices students.insert({"_key": "alice", "name": "Alice"}) students.insert({"_key": "bob", "name": "Bob"}) courses.insert({"_key": "CS101", "title": "Algorithms"}) courses.insert({"_key": "MA201", "title": "Calculus"}) # Insert edges edges.insert({"_from": "students/alice", "_to": "courses/CS101"}) edges.insert({"_from": "students/alice", "_to": "courses/MA201"}) edges.insert({"_from": "students/bob", "_to": "courses/CS101"}) # BFS traversal from a starting vertex via AQL cursor = db.aql.execute(""" FOR v, e, p IN 1..2 OUTBOUND 'students/alice' GRAPH 'school' OPTIONS { order: 'bfs', uniqueVertices: 'global' } RETURN { vertex: v, edge: e } """ ) for item in cursor: print(item["vertex"]["_key"]) # Check and delete graph print(db.has_graph("school")) db.delete_graph("school", drop_collections=True) ``` -------------------------------- ### Build and Test Documentation Source: https://github.com/arangodb/python-arango/blob/main/CONTRIBUTING.md Builds the project documentation using Sphinx and makes it available for viewing. Open docs/_build/index.html in your browser to see the built documentation. ```shell python -m sphinx docs docs/_build # Open docs/_build/index.html in your browser ``` -------------------------------- ### Explain AQL Query Plan Source: https://context7.com/arangodb/python-arango/llms.txt Explains the execution plan for an AQL query, providing estimated costs. ```python plan = db.aql.explain( "FOR s IN students FILTER s.age > @age RETURN s", bind_vars={"age": 18}, all_plans=False, ) print(plan["estimatedCost"]) ``` -------------------------------- ### Execute AQL Query with Cursor Options Source: https://github.com/arangodb/python-arango/blob/main/docs/cursor.md Demonstrates executing an AQL query, setting batch size, enabling count, and allowing retries. It shows how to iterate through the cursor using `has_more()`, `fetch()`, and `pop()`, and finally closing the cursor. ```python from arango import ArangoClient # Initialize the ArangoDB client. client = ArangoClient() # Connect to "test" database as root user. db = client.db('test', username='root', password='passwd') # Set up some test data to query against. db.collection('students').insert_many([ {'_key': 'Abby', 'age': 22}, {'_key': 'John', 'age': 18}, {'_key': 'Mary', 'age': 21}, {'_key': 'Suzy', 'age': 23}, {'_key': 'Dave', 'age': 20} ]) # Execute an AQL query which returns a cursor object. cursor = db.aql.execute( 'FOR doc IN students FILTER doc.age > @val RETURN doc', bind_vars={'val': 17}, batch_size=2, count=True, allow_retry=True ) while cursor.has_more(): try: cursor.fetch() except ConnectionError: # Retry the request. continue while not cursor.empty(): cursor.pop() # Delete the cursor from the server. cursor.close() ``` -------------------------------- ### Configure and Manage ArangoDB WAL Source: https://github.com/arangodb/python-arango/blob/main/docs/wal.md This snippet demonstrates how to initialize the ArangoDB client, connect to the _system database, and then configure, retrieve properties, list transactions, flush, and query WAL status. Ensure you have admin privileges. ```python from arango import ArangoClient # Initialize the ArangoDB client. client = ArangoClient() # Connect to "_system" database as root user. sys_db = client.db('_system', username='root', password='passwd') # Get the WAL API wrapper. wal = sys_db.wal # Configure WAL properties. wal.configure( historic_logs=15, oversized_ops=False, log_size=30000000, reserve_logs=5, throttle_limit=0, throttle_wait=16000 ) # Retrieve WAL properties. wal.properties() # List WAL transactions. wal.transactions() # Flush WAL with garbage collection. wal.flush(garbage_collect=True) # Get the available ranges of tick values. wal.tick_ranges() # Get the last available tick value. wal.last_tick() # Get recent WAL operations. wal.tail() ``` -------------------------------- ### Initialize ArangoDB Client and Access Cluster API Source: https://github.com/arangodb/python-arango/blob/main/docs/cluster.md Demonstrates initializing the ArangoDB client and accessing the cluster API for administrative tasks. Connects to the _system database as the root user. ```python from arango import ArangoClient # Initialize the ArangoDB client. client = ArangoClient() # Connect to "_system" database as root user. sys_db = client.db('_system', username='root', password='passwd') # Get the Cluster API wrapper. cluster = sys_db.cluster ``` -------------------------------- ### Get Pregel Job Details Source: https://github.com/arangodb/python-arango/blob/main/docs/pregel.md Retrieves the details of a specific Pregel job by its ID. ```APIDOC ## GET /_api/control_pregel/{job_id} ### Description Retrieves details of a Pregel job. ### Method GET ### Endpoint /_api/control_pregel/{job_id} ### Parameters #### Path Parameters - **job_id** (integer) - Required - The ID of the Pregel job to retrieve. ### Response #### Success Response (200) - **state** (string) - The current state of the Pregel job. - **progress** (float) - The progress of the Pregel job. - **result** (object) - The result of the Pregel job (if completed and stored). #### Response Example ```json { "state": "running", "progress": 0.5, "result": null } ``` ``` -------------------------------- ### Manage Users and Permissions Source: https://context7.com/arangodb/python-arango/llms.txt Create, list, grant, check, reset, update, and delete users and their permissions on databases and collections. Requires the `_system` database context. ```python from arango import ArangoClient client = ArangoClient() sys_db = client.db("_system", username="root", password="passwd") # Create a user sys_db.create_user( username="alice", password="secret", active=True, extra={"department": "engineering"}, ) # List users for u in sys_db.users(): print(u["username"], u["active"]) # Grant read-write on database, read-only on a specific collection sys_db.update_permission("alice", "rw", "myapp") sys_db.update_permission("alice", "ro", "myapp", "sensitive_data") # Check permissions print(sys_db.permission("alice", "myapp")) # 'rw' print(sys_db.permission("alice", "myapp", "sensitive_data")) # 'ro' # Reset to inherited default sys_db.reset_permission("alice", "myapp", "sensitive_data") # Update and delete sys_db.update_user("alice", password="newpassword", active=True) sys_db.delete_user("alice", ignore_missing=True) ``` -------------------------------- ### Initialize ArangoClient Source: https://context7.com/arangodb/python-arango/llms.txt Instantiate the ArangoClient with host URLs and optional configurations like HTTP client, compression, and TLS settings. Supports single hosts, clusters with load balancing, and custom HTTP clients. ```python from arango import ArangoClient from arango.http import DefaultHTTPClient, DeflateRequestCompression # Single host – basic usage client = ArangoClient(hosts="http://localhost:8529") # Cluster with round-robin load balancing client = ArangoClient( hosts=["http://coord1:8529", "http://coord2:8529", "http://coord3:8529"], host_resolver="roundrobin", resolver_max_tries=6, ) # Custom HTTP client with tuned pool & retries http = DefaultHTTPClient( request_timeout=30, retry_attempts=5, backoff_factor=0.5, pool_connections=20, pool_maxsize=20, ) # Enable deflate request compression and gzip response compression client = ArangoClient( hosts="http://localhost:8529", http_client=http, request_compression=DeflateRequestCompression(threshold=512, level=6), response_compression="gzip", verify_override=True, # enforce TLS cert verification ) print(client.hosts) # ['http://localhost:8529'] print(client.version) # e.g. '8.3.2' client.close() ``` -------------------------------- ### Insert Document Source: https://context7.com/arangodb/python-arango/llms.txt Inserts a single document into a collection and retrieves metadata. Use `return_new=True` to get the full document back. ```python meta = students.insert({"_key": "S001", "name": "Alice", "grade": "A"}) print(meta["_id"], meta["_rev"]) ``` ```python meta = students.insert({"name": "Bob", "grade": "B"}, return_new=True) print(meta["new"]) ``` -------------------------------- ### Basic ArangoDB Operations with Python Source: https://github.com/arangodb/python-arango/blob/main/README.md Connect to ArangoDB, create a database and collection, add an index, insert documents, and execute an AQL query. ```python from arango import ArangoClient # Initialize the client for ArangoDB. client = ArangoClient(hosts="http://localhost:8529") # Connect to "_system" database as root user. sys_db = client.db("_system", username="root", password="passwd") # Create a new database named "test". sys_db.create_database("test") # Connect to "test" database as root user. db = client.db("test", username="root", password="passwd") # Create a new collection named "students". students = db.create_collection("students") # Add a persistent index to the collection. students.add_index({'type': 'persistent', 'fields': ['name'], 'unique': True}) # Insert new documents into the collection. students.insert({"name": "jane", "age": 39}) students.insert({"name": "josh", "age": 18}) students.insert({"name": "judy", "age": 21}) # Execute an AQL query and iterate through the result cursor. cursor = db.aql.execute("FOR doc IN students RETURN doc") student_names = [document["name"] for document in cursor] ``` -------------------------------- ### Graph Operations Source: https://context7.com/arangodb/python-arango/llms.txt Demonstrates creating vertex and edge collections, inserting vertices and edges, and performing a Breadth-First Search (BFS) traversal. It also shows how to check for the existence of a graph and delete it. ```APIDOC ## Graph Operations This section covers the creation and manipulation of graph structures within ArangoDB using the Python driver. ### Create Vertex and Edge Collections ```python students = graph.create_vertex_collection("students") courses = graph.create_vertex_collection("courses") edges = graph.create_edge_definition( edge_collection="enrolled_in", from_vertex_collections=["students"], to_vertex_collections=["courses"], ) ``` ### Insert Vertices ```python students.insert({"_key": "alice", "name": "Alice"}) students.insert({"_key": "bob", "name": "Bob"}) courses.insert({"_key": "CS101", "title": "Algorithms"}) courses.insert({"_key": "MA201", "title": "Calculus"}) ``` ### Insert Edges ```python edges.insert({"_from": "students/alice", "_to": "courses/CS101"}) edges.insert({"_from": "students/alice", "_to": "courses/MA201"}) edges.insert({"_from": "students/bob", "_to": "courses/CS101"}) ``` ### BFS Traversal ```python cursor = db.aql.execute(""" FOR v, e, p IN 1..2 OUTBOUND 'students/alice' GRAPH 'school' OPTIONS { order: 'bfs', uniqueVertices: 'global' } RETURN { vertex: v, edge: e } """) for item in cursor: print(item["vertex"]["_key"]) ``` ### Check and Delete Graph ```python print(db.has_graph("school")) db.delete_graph("school", drop_collections=True) ``` ``` -------------------------------- ### Document CRUD - Collection Level Source: https://context7.com/arangodb/python-arango/llms.txt Perform insert, get, update, replace, and delete operations on documents within a specific collection. ```APIDOC ## Document CRUD - Collection Level ### Description Perform insert, get, update, replace, and delete operations on documents within a specific collection. ### Methods - `insert(document, return_new=False, **kwargs)`: Inserts a single document. - `insert_many(documents, **kwargs)`: Inserts multiple documents in bulk. - `get(key, **kwargs)`: Retrieves a single document by its key. - `update(document, **kwargs)`: Partially updates an existing document. - `replace(document, **kwargs)`: Replaces an existing document with new data. - `delete(key, ignore_missing=False, **kwargs)`: Deletes a document by its key. - `__iter__()`: Iterates over all documents in the collection. - `__len__()`: Returns the total number of documents in the collection. - `__contains__(key)`: Checks if a document with the given key exists. ### Request Example (Insert) ```python from arango import ArangoClient client = ArangoClient() db = client.db("test", username="root", password="passwd") students = db.collection("students") meta = students.insert({"_key": "S001", "name": "Alice", "grade": "A"}) print(meta["_id"], meta["_rev"]) ``` ### Request Example (Get) ```python doc = students.get("S001") print(doc) ``` ### Request Example (Update) ```python students.update({"_key": "S001", "grade": "A+"}) ``` ### Request Example (Delete) ```python students.delete("S001", ignore_missing=True) ``` ### Request Example (Iteration) ```python for doc in students: print(doc["name"]) ``` ### Request Example (Count) ```python print(len(students)) ``` ### Request Example (Membership Check) ```python print("S002" in students) ``` ``` -------------------------------- ### Create and Use Custom AQL Function Source: https://context7.com/arangodb/python-arango/llms.txt Creates a custom AQL function, executes it, and then deletes it. ```python db.aql.create_function( name="MYAPP::DOUBLE", code="function(v) { return v * 2; }", ) cursor = db.aql.execute("RETURN MYAPP::DOUBLE(21)") print(list(cursor)) ``` ```python db.aql.delete_function("MYAPP::DOUBLE") ``` -------------------------------- ### Rebalance Cluster Shard Distribution Source: https://github.com/arangodb/python-arango/blob/main/docs/cluster.md Initiates the rebalancing of shard distribution across the cluster. This feature is available starting with ArangoDB version 3.10. ```python # Rebalance the distribution of shards. Available with ArangoDB 3.10+. cluster.rebalance() ``` -------------------------------- ### Manage ArangoDB Backups with Python Source: https://github.com/arangodb/python-arango/blob/main/docs/backup.md Demonstrates the full lifecycle of ArangoDB backup operations including creation, retrieval, upload, download, restore, and deletion. Ensure the ArangoDB client is initialized and connected to the desired database. ```python from arango import ArangoClient # Initialize the ArangoDB client. client = ArangoClient() # Connect to "_system" database as root user. sys_db = client.db( '_system', username='root', password='passwd', auth_method='jwt' ) # Get the backup API wrapper. backup = sys_db.backup # Create a backup. result = backup.create( label='foo', allow_inconsistent=True, force=False, timeout=1000 ) backup_id = result['backup_id'] # Retrieve details on all backups backup.get() # Retrieve details on a specific backup. backup.get(backup_id=backup_id) # Upload a backup to a remote repository. result = backup.upload( backup_id=backup_id, repository='local://tmp/backups', config={'local': {'type': 'local'}} ) upload_id = result['upload_id'] # Get status of an upload. backup.upload(upload_id=upload_id) # Abort an upload. backup.upload(upload_id=upload_id, abort=True) # Download a backup from a remote repository. result = backup.download( backup_id=backup_id, repository='local://tmp/backups', config={'local': {'type': 'local'}} ) download_id = result['download_id'] # Get status of an download. backup.download(download_id=download_id) # Abort an download. backup.download(download_id=download_id, abort=True) # Restore from a backup. backup.restore(backup_id) # Delete a backup. backup.delete(backup_id) ``` -------------------------------- ### Create ArangoSearch View and Custom Analyzer Source: https://context7.com/arangodb/python-arango/llms.txt Demonstrates creating an ArangoSearch view for full-text search and defining a custom analyzer. It also shows how to perform a full-text search using AQL and list available analyzers. ```python from arango import ArangoClient client = ArangoClient() db = client.db("test", username="root", password="passwd") # Create an ArangoSearch view view = db.create_arangosearch_view( name="students_view", properties={ "links": { "students": { "analyzers": ["text_en"], "fields": {"name": {}, "bio": {}}, "includeAllFields": False, "storeValues": "none", } }, "primarySort": [{"field": "name", "direction": "asc"}] }, ) print(view["name"]) # Full-text AQL search cursor = db.aql.execute(""" FOR doc IN students_view SEARCH ANALYZER(doc.name IN TOKENS('alice', 'text_en'), 'text_en') SORT BM25(doc) DESC RETURN doc ") # Create a custom analyzer db.create_analyzer( name="my_ngram", analyzer_type="ngram", properties={"min": 2, "max": 4, "preserveOriginal": True}, features=["frequency", "norm", "position"], ) # List analyzers for a in db.analyzers(): print(a["name"]) ``` -------------------------------- ### Initialize ArangoClient Source: https://context7.com/arangodb/python-arango/llms.txt The ArangoClient is the main entry point for interacting with ArangoDB. It can be initialized with single or multiple host URLs and supports various configurations for HTTP clients, compression, and TLS settings. ```APIDOC ## Initialize ArangoClient `ArangoClient` is the main entry point, accepting one or more host URLs plus optional HTTP client, serializer, compressor, and TLS settings. ### Method Initialization ### Parameters #### Path Parameters - **hosts** (string or list[string]) - Required - One or more ArangoDB host URLs. - **host_resolver** (string) - Optional - Strategy for resolving hosts in a cluster (e.g., "roundrobin"). - **resolver_max_tries** (int) - Optional - Maximum attempts for host resolution. - **http_client** (object) - Optional - Custom HTTP client instance. - **request_compression** (object) - Optional - Configuration for request compression. - **response_compression** (string) - Optional - Configuration for response compression (e.g., "gzip"). - **verify_override** (bool) - Optional - Enforce TLS certificate verification. ### Request Example ```python from arango import ArangoClient # Single host client = ArangoClient(hosts="http://localhost:8529") # Cluster with round-robin load balancing client = ArangoClient( hosts=["http://coord1:8529", "http://coord2:8529", "http://coord3:8529"], host_resolver="roundrobin", resolver_max_tries=6, ) # Custom HTTP client with tuned pool & retries from arango.http import DefaultHTTPClient http = DefaultHTTPClient( request_timeout=30, retry_attempts=5, backoff_factor=0.5, pool_connections=20, pool_maxsize=20, ) client = ArangoClient( hosts="http://localhost:8529", http_client=http, ) # Enable deflate request compression and gzip response compression from arango.http import DeflateRequestCompression client = ArangoClient( hosts="http://localhost:8529", request_compression=DeflateRequestCompression(threshold=512, level=6), response_compression="gzip", verify_override=True, ) ``` ### Response #### Success Response - **hosts** (list[string]) - The configured host URLs. - **version** (string) - The ArangoDB server version. ### Response Example ```python print(client.hosts) # ['http://localhost:8529'] print(client.version) # e.g. '8.3.2' client.close() ``` ``` -------------------------------- ### Overload Control Source: https://context7.com/arangodb/python-arango/llms.txt Demonstrates how to cap the maximum server-side queue time to gracefully handle server overload and dynamically adjust the limit. ```APIDOC ## Overload Control ### Description Cap the maximum server-side queue time to gracefully handle server overload. ### Method ```python from arango import ArangoClient from arango.exceptions import ArangoServerError client = ArangoClient() db = client.db("test", username="root", password="passwd") # Begin a controlled session: reject if server queues > 2 s controlled = db.begin_controlled_execution(max_queue_time_seconds=2.0) try: result = controlled.aql.execute("FOR s IN students RETURN s") docs = list(result) except ArangoServerError as err: print(f"Server overloaded, queue time exceeded: {err}") # Inspect queue time for the last request print(controlled.last_queue_time) # e.g. 0.012 # Dynamically adjust the limit controlled.adjust_max_queue_time(5.0) # Disable the limit controlled.adjust_max_queue_time(None) ``` ``` -------------------------------- ### Execute Simple AQL Query Source: https://context7.com/arangodb/python-arango/llms.txt Executes a simple AQL query and returns a cursor for the results. ```python cursor = db.aql.execute("FOR doc IN students RETURN doc") names = [doc["name"] for doc in cursor] ``` -------------------------------- ### Run Unit Tests with Coverage Source: https://github.com/arangodb/python-arango/blob/main/CONTRIBUTING.md Executes unit tests and generates an HTML coverage report. Open the generated htmlcov/index.html file in your browser to view the report. ```shell pytest --cov=arango --cov-report=html # Open htmlcov/index.html in your browser ``` -------------------------------- ### WAL Configuration Source: https://github.com/arangodb/python-arango/blob/main/docs/wal.md Configure WAL properties such as historic logs, log size, and throttle settings. ```APIDOC ## WAL Configuration ### Description Configure WAL properties. ### Method `wal.configure()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **historic_logs** (integer) - Number of historic WAL logs to keep. - **oversized_ops** (boolean) - Whether to allow oversized operations. - **log_size** (integer) - The size of each WAL log file in bytes. - **reserve_logs** (integer) - Number of WAL logs to reserve. - **throttle_limit** (integer) - The throttle limit for WAL operations. - **throttle_wait** (integer) - The wait time in milliseconds for throttling. ### Request Example ```python wal.configure( historic_logs=15, oversized_ops=False, log_size=30000000, reserve_logs=5, throttle_limit=0, throttle_wait=16000 ) ``` ### Response #### Success Response (200) Returns `True` if configuration is successful. #### Response Example ```json true ``` ``` -------------------------------- ### AQL - Execute Queries Source: https://context7.com/arangodb/python-arango/llms.txt Run ArangoDB Query Language (AQL) queries with bind variables, cursors, and streaming. ```APIDOC ## AQL — Execute Queries ### Description Run ArangoDB Query Language (AQL) queries with bind variables, cursors, and streaming. ### Methods - `execute(query, bind_vars=None, count=False, batch_size=None, stream=False, ttl=None)`: Executes an AQL query. - `validate(query)`: Validates an AQL query without executing it. - `explain(query, bind_vars=None, all_plans=False)`: Explains the query plan. - `create_function(name, code)`: Creates a custom AQL function. - `delete_function(name)`: Deletes a custom AQL function. ### Request Example (Simple Query) ```python from arango import ArangoClient client = ArangoClient() db = client.db("test", username="root", password="passwd") cursor = db.aql.execute("FOR doc IN students RETURN doc") names = [doc["name"] for doc in cursor] ``` ### Request Example (Query with Bind Variables) ```python cursor = db.aql.execute( "FOR s IN students FILTER s.grade == @grade RETURN s", bind_vars={"grade": "A"}, count=True, batch_size=100, ) print(cursor.count()) for doc in cursor: print(doc["name"]) ``` ### Request Example (Streaming Query) ```python cursor = db.aql.execute( "FOR i IN 1..1000000 RETURN i", stream=True, ttl=60, ) total = sum(cursor) ``` ### Request Example (Validate Query) ```python result = db.aql.validate("FOR doc IN students RETURN doc.name") print(result["parsed"]) ``` ### Request Example (Explain Query) ```python plan = db.aql.explain( "FOR s IN students FILTER s.age > @age RETURN s", bind_vars={"age": 18}, all_plans=False, ) print(plan["estimatedCost"]) ``` ### Request Example (Create Custom AQL Function) ```python db.aql.create_function( name="MYAPP::DOUBLE", code="function(v) { return v * 2; }", ) cursor = db.aql.execute("RETURN MYAPP::DOUBLE(21)") print(list(cursor)) ``` ### Request Example (Delete Custom AQL Function) ```python db.aql.delete_function("MYAPP::DOUBLE") ``` ``` -------------------------------- ### Execute AQL Query with Bind Variables Source: https://context7.com/arangodb/python-arango/llms.txt Executes an AQL query using bind variables for dynamic filtering. `count=True` enables retrieving the total count of matching documents. ```python cursor = db.aql.execute( "FOR s IN students FILTER s.grade == @grade RETURN s", bind_vars={"grade": "A"}, count=True, batch_size=100, ) print(cursor.count()) ``` -------------------------------- ### Manage Foxx Services with Python-Arango Source: https://github.com/arangodb/python-arango/blob/main/docs/foxx.md Use this snippet to create, update, replace, and delete Foxx services directly from Python. Ensure the ArangoDB client is initialized and connected to the desired database. ```python from arango import ArangoClient # Initialize the ArangoDB client. client = ArangoClient() # Connect to "_system" database as root user. db = client.db('_system', username='root', password='passwd') # Get the Foxx API wrapper. foxx = db.foxx # Define the test mount point. service_mount = '/test_mount' # Create a service by providing a file directly. foxx.create_service_with_file( mount=service_mount, filename='/home/user/service.zip', development=True, setup=True, legacy=True ) # Update (upgrade) a service by providing a file directly. foxx.update_service_with_file( mount=service_mount, filename='/home/user/service.zip', teardown=False, setup=True, legacy=True, force=False ) # Replace a service by providing a file directly. foxx.replace_service_with_file( mount=service_mount, filename='/home/user/service.zip', teardown=False, setup=True, legacy=True, force=False ) # Delete a service. foxx.delete_service(service_mount) ``` -------------------------------- ### Use System Default CA Bundle Source: https://github.com/arangodb/python-arango/blob/main/docs/certificates.md Connects to the ArangoDB server using the system's default CA bundle for TLS certificate verification. ```python client = ArangoClient(hosts="https://localhost:8529", verify_override=True) ``` -------------------------------- ### User and Permission Management Source: https://context7.com/arangodb/python-arango/llms.txt Demonstrates how to create, list, grant permissions to, check, update, and delete users in ArangoDB using the Python client. ```APIDOC ## User and Permission Management ### Description Create users and grant fine-grained access to databases and collections. ### Method ```python from arango import ArangoClient client = ArangoClient() sys_db = client.db("_system", username="root", password="passwd") # Create a user sys_db.create_user( username="alice", password="secret", active=True, extra={"department": "engineering"}, ) # List users for u in sys_db.users(): print(u["username"], u["active"]) # Grant read-write on database, read-only on a specific collection sys_db.update_permission("alice", "rw", "myapp") sys_db.update_permission("alice", "ro", "myapp", "sensitive_data") # Check permissions print(sys_db.permission("alice", "myapp")) # 'rw' print(sys_db.permission("alice", "myapp", "sensitive_data")) # 'ro' # Reset to inherited default sys_db.reset_permission("alice", "myapp", "sensitive_data") # Update and delete sys_db.update_user("alice", password="newpassword", active=True) sys_db.delete_user("alice", ignore_missing=True) ``` ```