### AQL Query Explain Options Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure for specifying options when explaining an AQL query. ```json { "allPlans" : false, "maxNumberOfPlans" : 1, "optimizer" : { "rules" : [ "-all", "+use-indexe-for-sort" ] } } ``` -------------------------------- ### AQL Query Tracking Configuration Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure for configuring AQL query tracking. ```json { "enabled": true, "trackSlowQueries": true, "trackBindVars": true, "maxSlowQueries": 64, "slowQueryThreshold": 10, "slowStreamingQueryThreshold": 10, "maxQueryStringLength": 4096 } ``` -------------------------------- ### AQL Query Optimizer Rules Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example of configuring AQL query optimizer rules, including setting the maximum number of plans and specifying rules to apply or exclude. ```json { "maxPlans": 1, "optimizer": { "rules": [ "-all", "+remove-unnecessary-filters" ] } } ``` -------------------------------- ### create_service(mount, service, headers=None, development=None, setup=None, legacy=None) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Installs a new Foxx service at the specified mount path. Supports various installation options. ```APIDOC ## create_service(mount, service, headers=None, development=None, setup=None, legacy=None) ### Description Installs the given new service at the given mount path. ### Method POST (implied) ### Endpoint /_api/foxx/services/{mount} ### Parameters #### Path Parameters - **mount** (str) - Required - Mount path the service should be installed at. #### Request Body - **service** (Any) - Required - Service payload. Can be a JSON string, a file-like object, or a multipart form. #### Query Parameters - **headers** (dict | None) - Optional - Request headers. - **development** (bool | None) - Optional - Whether to install the service in development mode. - **setup** (bool | None) - Optional - Whether to run the service setup script. - **legacy** (bool | None) - Optional - Whether to install in legacy mode. ### Response #### Success Response (200) - **metadata** (dict) - Service metadata. ### Response Example { "example": "{\"name\": \"my-new-service\", \"version\": \"1.0.0\"}" } ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/arangodb/python-arango-async/blob/main/CONTRIBUTING.md Installs project dependencies and sets up pre-commit hooks for development. Activate your virtual environment before running these commands. ```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 python-arango-async Source: https://github.com/arangodb/python-arango-async/blob/main/docs/index.md Install the python-arango-async library using pip. Ensure you have the latest version. ```bash ~$ pip install python-arango-async --upgrade ``` -------------------------------- ### AQL Cache Properties Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure representing the configuration properties for the AQL query cache. ```json { "mode" : "demand", "maxResults" : 128, "maxResultsSize" : 268435456, "maxEntrySize" : 16777216, "includeSystem" : false } ``` -------------------------------- ### Install python-arango-async Source: https://github.com/arangodb/python-arango-async/blob/main/README.md Install the python-arango-async driver using pip. Ensure you have Python 3.10+ and ArangoDB 3.11+ installed. ```shell pip install python-arango-async --upgrade ``` -------------------------------- ### Query Execution Profile Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure representing the profile of an AQL query execution. ```json { "initializing" : 0.0000028529999838156073, "parsing" : 0.000029285000010759177, "optimizing ast" : 0.0000040699999885873694, "loading collections" : 0.000012807000018710823, "instantiating plan" : 0.00002348999998957879, "optimizing plan" : 0.00006598600000984334, "instantiating executors" : 0.000027471999999306718, "executing" : 0.7550992429999894, "finalizing" : 0.00004103500000951499 } ``` -------------------------------- ### ArangoDB Python Async Transaction Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/transaction.md Demonstrates the full lifecycle of a transaction, including starting, inserting data, checking status, committing, aborting, and fetching existing transactions. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Get the API wrapper for "students" collection. students = db.collection("students") # Begin a transaction. Read and write collections must be declared ahead of # time. This returns an instance of TransactionDatabase, database-level # API wrapper tailored specifically for executing transactions. txn_db = await db.begin_transaction(read=students.name, write=students.name) # The API wrapper is specific to a single transaction with a unique ID. trx_id = txn_db.transaction_id # Child wrappers are also tailored only for the specific transaction. txn_aql = txn_db.aql txn_col = txn_db.collection("students") # API execution context is always set to "transaction". assert txn_db.context == "transaction" assert txn_aql.context == "transaction" assert txn_col.context == "transaction" assert "_rev" in await txn_col.insert({"_key": "Abby"}) assert "_rev" in await txn_col.insert({"_key": "John"}) assert "_rev" in await txn_col.insert({"_key": "Mary"}) # Check the transaction status. status = await txn_db.transaction_status() # Commit the transaction. await txn_db.commit_transaction() assert await students.has("Abby") assert await students.has("John") assert await students.has("Mary") assert await students.count() == 3 # Begin another transaction. Note that the wrappers above are specific to # the last transaction and cannot be reused. New ones must be created. txn_db = await db.begin_transaction(read=students.name, write=students.name) txn_col = txn_db.collection("students") assert "_rev" in await txn_col.insert({"_key": "Kate"}) assert "_rev" in await txn_col.insert({"_key": "Mike"}) assert "_rev" in await txn_col.insert({"_key": "Lily"}) assert await txn_col.count() == 6 # Abort the transaction await txn_db.abort_transaction() assert not await students.has("Kate") assert not await students.has("Mike") assert not await students.has("Lily") assert await students.count() == 3 # transaction is aborted so txn_col cannot be used # Fetch an existing transaction. Useful if you have received a Transaction ID # from an external system. original_txn = await db.begin_transaction(write='students') txn_col = original_txn.collection('students') assert '_rev' in await txn_col.insert({'_key': 'Chip'}) txn_db = db.fetch_transaction(original_txn.transaction_id) txn_col = txn_db.collection('students') assert '_rev' in await txn_col.insert({'_key': 'Alya'}) await txn_db.abort_transaction() ``` -------------------------------- ### Access Token Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md An example JSON structure representing a user access token. This format is used when creating or managing access tokens. ```json { "id" : 1, "name" : "Token for Service A", "valid_until" : 1782864000, "created_at" : 1765543306, "fingerprint" : "v1...71227d", "active" : true, "token" : "v1.7b2265223a3137471227d" } ``` -------------------------------- ### Create User (Synchronous) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/migration.md Example of creating a new user using the synchronous python-arango driver. ```python sys_db.create_user( username="johndoe@gmail.com", password="first_password", active=True, extra={"team": "backend", "title": "engineer"} ) ``` -------------------------------- ### Query Execution Statistics Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure detailing the statistics of an AQL query execution. ```json { "writesExecuted" : 0, "writesIgnored" : 0, "documentLookups" : 0, "seeks" : 0, "scannedFull" : 2, "scannedIndex" : 0, "cursorsCreated" : 0, "cursorsRearmed" : 0, "cacheHits" : 0, "cacheMisses" : 0, "filtered" : 0, "httpRequests" : 0, "executionTime" : 0.00019362399999067748, "peakMemoryUsage" : 0, "intermediateCommits" : 0 } ``` -------------------------------- ### ArangoDB Client Initialization Source: https://github.com/arangodb/python-arango-async/blob/main/docs/document.md Basic setup for initializing the ArangoDB client using python-arango-async. Requires importing the ArangoClient and Auth classes. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth ``` -------------------------------- ### Start Local ArangoDB Instance Source: https://github.com/arangodb/python-arango-async/blob/main/CONTRIBUTING.md Launches a local ArangoDB instance using the provided script. Docker is a prerequisite for this command. ```shell ./starter.sh # Requires docker ``` -------------------------------- ### Async API Execution Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/async.md Demonstrates initiating asynchronous API executions, managing async jobs, retrieving results, and handling errors. Use this for fire-and-forget style requests where immediate results are not required. ```python import time from arangoasync import ArangoClient from arangoasync.auth import Auth from arangoasync.errno import HTTP_BAD_PARAMETER from arangoasync.exceptions import ( AQLQueryExecuteError, AsyncJobCancelError, AsyncJobClearError, ) # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Begin async execution. This returns an instance of AsyncDatabase, a # database-level API wrapper tailored specifically for async execution. async_db = db.begin_async_execution(return_result=True) # Child wrappers are also tailored for async execution. async_aql = async_db.aql async_col = async_db.collection("students") # API execution context is always set to "async". assert async_db.context == "async" assert async_aql.context == "async" assert async_col.context == "async" # On API execution, AsyncJob objects are returned instead of results. job1 = await async_col.insert({"_key": "Neal"}) job2 = await async_col.insert({"_key": "Lily"}) job3 = await async_aql.execute("RETURN 100000") job4 = await async_aql.execute("INVALID QUERY") # Fails due to syntax error. # Retrieve the status of each async job. for job in [job1, job2, job3, job4]: # Job status can be "pending" or "done". assert await job.status() in {"pending", "done"} # Let's wait until the jobs are finished. while await job.status() != "done": time.sleep(0.1) # Retrieve the results of successful jobs. metadata = await job1.result() assert metadata["_id"] == "students/Neal" metadata = await job2.result() assert metadata["_id"] == "students/Lily" cursor = await job3.result() assert await cursor.next() == 100000 # If a job fails, the exception is propagated up during result retrieval. try: result = await job4.result() except AQLQueryExecuteError as err: assert err.http_code == HTTP_BAD_PARAMETER # Cancel a job. Only pending jobs still in queue may be cancelled. # Since job3 is done, there is nothing to cancel and an exception is raised. try: await job3.cancel() except AsyncJobCancelError as err: print(err.message) # Clear the result of a job from ArangoDB server to free up resources. # Result of job4 was removed from the server automatically upon retrieval, # so attempt to clear it raises an exception. try: await job4.clear() except AsyncJobClearError as err: print(err.message) # List the IDs of the first 100 async jobs completed. jobs_done = await db.async_jobs(status="done", count=100) # List the IDs of the first 100 async jobs still pending. jobs_pending = await db.async_jobs(status='pending', count=100) # Clear all async jobs still sitting on the server. await db.clear_async_jobs() ``` -------------------------------- ### Manage Graphs, Collections, and Perform Graph Traversal Source: https://github.com/arangodb/python-arango-async/blob/main/docs/overview.md This example demonstrates creating and managing a graph, including vertex and edge collections, inserting documents, and performing a graph traversal query. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Get the API wrapper for graph "school". if await db.has_graph("school"): graph = db.graph("school") else: graph = await db.create_graph("school") # Create vertex collections for the graph. students = await graph.create_vertex_collection("students") lectures = await graph.create_vertex_collection("lectures") # Create an edge definition (relation) for the graph. edges = await graph.create_edge_definition( edge_collection="register", from_vertex_collections=["students"], to_vertex_collections=["lectures"] ) # Insert vertex documents into "students" (from) vertex collection. await students.insert({"_key": "01", "full_name": "Anna Smith"}) await students.insert({"_key": "02", "full_name": "Jake Clark"}) await students.insert({"_key": "03", "full_name": "Lisa Jones"}) # Insert vertex documents into "lectures" (to) vertex collection. await lectures.insert({"_key": "MAT101", "title": "Calculus"}) await lectures.insert({"_key": "STA101", "title": "Statistics"}) await lectures.insert({"_key": "CSC101", "title": "Algorithms"}) # Insert edge documents into "register" edge collection. await edges.insert({"_from": "students/01", "_to": "lectures/MAT101"}) await edges.insert({"_from": "students/01", "_to": "lectures/STA101"}) await edges.insert({"_from": "students/01", "_to": "lectures/CSC101"}) await edges.insert({"_from": "students/02", "_to": "lectures/MAT101"}) await edges.insert({"_from": "students/02", "_to": "lectures/STA101"}) await edges.insert({"_from": "students/03", "_to": "lectures/CSC101"}) # Traverse the graph in outbound direction, breath-first. 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} """ async with await db.aql.execute(query) as cursor: async for doc in cursor: print(doc) ``` -------------------------------- ### Create User (Asynchronous) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/migration.md Example of creating a new user using the asynchronous python-arango-async driver with helper types for better type hinting. ```python from arangoasync.typings import UserInfo user_info = UserInfo( username="johndoe@gmail.com", password="first_password", active=True, extra={"team": "backend", "title": "engineer"} ) await sys_db.create_user(user_info) ``` -------------------------------- ### download(mount) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Downloads a zip bundle of the service directory. If development mode is enabled, a new bundle is created; otherwise, it represents the installed version. ```APIDOC ## download(mount) ### Description Downloads a zip bundle of the service directory. If development mode is enabled, a new bundle is created; otherwise, it represents the installed version. ### Parameters #### Path Parameters * **mount** (str) - Required - Service mount path. ### Returns Service bundle zip in raw bytes form. * **Return type:** bytes ### Raises [**FoxxDownloadError**](errors.md#arangoasync.exceptions.FoxxDownloadError) – If download fails. ### References - [download-a-service-bundle](https://docs.arango.ai/arangodb/stable/develop/http-api/foxx/#download-a-service-bundle) ``` -------------------------------- ### Custom HTTP Client Implementation Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Example of how to implement a custom HTTP client by inheriting from the abstract base class. This is useful for integrating with different HTTP libraries or custom network configurations. ```python class MyCustomHTTPClient(HTTPClient): def create_session(self, host): pass async def close_session(self, session): pass async def send_request(self, session, request): pass ``` -------------------------------- ### Custom HTTP Client using httpx.AsyncClient Source: https://github.com/arangodb/python-arango-async/blob/main/docs/http.md Implement a custom HTTP client by extending `HTTPClient` and utilizing `httpx.AsyncClient`. This example shows how to manage sessions, timeouts, and SSL contexts for requests. ```python import httpx import ssl from typing import Any, Optional from arangoasync.exceptions import ClientConnectionError from arangoasync.http import HTTPClient from arangoasync.request import Request from arangoasync.response import Response class HttpxHTTPClient(HTTPClient): """HTTP client implementation on top of httpx.AsyncClient. Args: limits (httpx.Limits | None): Connection pool limits.n timeout (httpx.Timeout | float | None): Request timeout settings. ssl_context (ssl.SSLContext | bool): SSL validation mode. `True` (default) uses httpx’s default validation (system CAs). `False` disables SSL checks. Or pass a custom `ssl.SSLContext`. """ def __init__( self, limits: Optional[httpx.Limits] = None, timeout: Optional[httpx.Timeout | float] = None, ssl_context: bool | ssl.SSLContext = True, ) -> None: self._limits = limits or httpx.Limits( max_connections=100, max_keepalive_connections=20 ) self._timeout = timeout or httpx.Timeout(300.0, connect=60.0) if ssl_context is True: self._verify: bool | ssl.SSLContext = True elif ssl_context is False: self._verify = False else: self._verify = ssl_context def create_session(self, host: str) -> httpx.AsyncClient: return httpx.AsyncClient( base_url=host, limits=self._limits, timeout=self._timeout, verify=self._verify, ) async def close_session(self, session: httpx.AsyncClient) -> None: await session.aclose() async def send_request( self, session: httpx.AsyncClient, request: Request, ) -> Response: auth: Any = None if request.auth is not None: auth = httpx.BasicAuth( username=request.auth.username, password=request.auth.password, ) try: resp = await session.request( method=request.method.name, url=request.endpoint, headers=request.normalized_headers(), params=request.normalized_params(), content=request.data, auth=auth, ) raw_body = resp.content return Response( method=request.method, url=str(resp.url), headers=resp.headers, status_code=resp.status_code, status_text=resp.reason_phrase, raw_body=raw_body, ) except httpx.HTTPError as e: raise ClientConnectionError(str(e)) from e ``` -------------------------------- ### service(mount) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Retrieves metadata for a specific Foxx service installed at the given mount path. ```APIDOC ## service(mount) ### Description Return service metadata. ### Method GET (implied) ### Endpoint /_api/foxx/service/{mount} ### Parameters #### Path Parameters - **mount** (str) - Required - Service mount path (e.g “/_admin/aardvark”). ### Response #### Success Response (200) - **metadata** (dict) - Service metadata. ### Response Example { "example": "{\"name\": \"my-service\", \"version\": \"1.0.0\"}" } ``` -------------------------------- ### replace_service(mount, service, headers=None, teardown=None, setup=None, legacy=None, force=None) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Replaces an existing Foxx service at the given mount path with a new service. Supports various options including teardown, setup, legacy mode, and force replacement. ```APIDOC ## replace_service(mount, service, headers=None, teardown=None, setup=None, legacy=None, force=None) ### Description Replace an existing Foxx service at the given mount path. ### Method PUT (implied) ### Endpoint /_api/foxx/services/{mount} ### Parameters #### Path Parameters - **mount** (str) - Required - Mount path of the service to replace. #### Request Body - **service** (Any) - Required - Service payload (JSON string, file-like object, or multipart form). #### Query Parameters - **headers** (dict | None) - Optional - Optional request headers. - **teardown** (bool | None) - Optional - Whether to run the teardown script. - **setup** (bool | None) - Optional - Whether to run the setup script. - **legacy** (bool | None) - Optional - Whether to install in legacy mode. - **force** (bool | None) - Optional - Set to True to force service install even if no service is installed under given mount. ### Response #### Success Response (200) - **metadata** (dict) - Service metadata. ### Response Example { "example": "{\"name\": \"my-replaced-service\", \"version\": \"1.1.0\"}" } ``` -------------------------------- ### Example Python Edge Document Structure Source: https://github.com/arangodb/python-arango-async/blob/main/docs/document.md Shows the structure of an edge document in Python, highlighting the additional '_from' and '_to' fields required for linking vertex documents. ```python { "_id": "friends/001", "_key": "001", "_rev": "_Wm3d4le--_", "_fro"': "students/john", "_to": "students/jane", "closeness": 9.5 } ``` -------------------------------- ### update_service(mount, service, headers=None, teardown=None, setup=None, legacy=None, force=None) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Upgrades an existing Foxx service at the given mount path. Supports various upgrade options including teardown, setup, legacy mode, and force upgrade. ```APIDOC ## update_service(mount, service, headers=None, teardown=None, setup=None, legacy=None, force=None) ### Description Upgrade a Foxx service at the given mount path. ### Method PATCH (implied) ### Endpoint /_api/foxx/services/{mount} ### Parameters #### Path Parameters - **mount** (str) - Required - Mount path of the service to upgrade. #### Request Body - **service** (Any) - Required - Service payload (JSON string, file-like object, or multipart form). #### Query Parameters - **headers** (dict | None) - Optional - Optional request headers. - **teardown** (bool | None) - Optional - Whether to run the teardown script. - **setup** (bool | None) - Optional - Whether to run the setup script. - **legacy** (bool | None) - Optional - Whether to upgrade in legacy mode. - **force** (bool | None) - Optional - Set to True to force service install even if no service is installed under given mount. ### Response #### Success Response (200) - **metadata** (dict) - Service metadata. ### Response Example { "example": "{\"name\": \"my-updated-service\", \"version\": \"1.2.0\"}" } ``` -------------------------------- ### Initialize Client, Manage Databases, Collections, and Query Data Source: https://github.com/arangodb/python-arango-async/blob/main/docs/overview.md This snippet demonstrates initializing the client using a context manager, creating a database and collection, adding an index, inserting documents, and executing an AQL query. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "_system" database as root user. sys_db = await client.db("_system", auth=auth) # Create a new database named "test". await sys_db.create_database("test") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Create a new collection named "students". students = await db.create_collection("students") # Add a persistent index to the collection. await students.add_index(type="persistent", fields=["name"], options={"unique": True}) # Insert new documents into the collection. await students.insert({"name": "jane", "age": 39}) await students.insert({"name": "josh", "age": 18}) await students.insert({"name": "judy", "age": 21}) # Execute an AQL query and iterate through the result cursor. cursor = await db.aql.execute("FOR doc IN students RETURN doc") async with cursor: student_names = [] async for doc in cursor: student_names.append(doc["name"]) ``` -------------------------------- ### Initialize Client Manually, Manage Databases, and List Collections Source: https://github.com/arangodb/python-arango-async/blob/main/docs/overview.md This snippet shows how to initialize the client without a context manager, create a database, list collections, and manually close the client. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth client = ArangoClient(hosts="http://localhost:8529") auth = Auth(username="root", password="passwd") sys_db = await client.db("_system", auth=auth) # Create a new database named "test". await sys_db.create_database("test") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # List all collections in the "test" database. collections = await db.collections() # Close the client when done. await client.close() ``` -------------------------------- ### Graph Properties Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Example JSON structure defining the properties of an ArangoDB graph. ```json { "_key" : "myGraph", "edgeDefinitions" : [ { "collection" : "edges", "from" : [ "startVertices" ], "to" : [ "endVertices" ] } ], "orphanCollections" : [ ], "_rev" : "_jJdpHEy--_", "_id" : "_graphs/myGraph", "name" : "myGraph" } ``` -------------------------------- ### Initialize Client and Execute Query with Properties Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Demonstrates initializing the ArangoDB client, connecting to a database with authentication, defining query properties, and executing an AQL query with these options. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth from arangoasync.typings import QueryProperties # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) properties = QueryProperties( allow_dirty_reads=True, allow_retry=False, fail_on_warning=True, fill_block_cache=False, full_count=True, intermediate_commit_count=1000, intermediate_commit_size=1048576, max_dnf_condition_members=10, max_nodes_per_callstack=100, max_number_of_plans=5, max_runtime=60.0, max_transaction_size=10485760, max_warning_count=10, optimizer={"rules": ["-all", "+use-indexes"]}, profile=1, satellite_sync_wait=10.0, skip_inaccessible_collections=True, spill_over_threshold_memory_usage=10485760, spill_over_threshold_num_rows=100000, stream=True, use_plan_cache=True, ) # The types are fully serializable. print(properties) await db.aql.execute( "FOR doc IN students RETURN doc", batch_size=1, options=properties, ) ``` -------------------------------- ### Basic ArangoDB Operations Source: https://github.com/arangodb/python-arango-async/blob/main/README.md Demonstrates initializing the client, connecting to a database, creating a database and collection, adding an index, inserting documents, and executing an AQL query. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth async def main(): # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "_system" database as root user. sys_db = await client.db("_system", auth=auth) # Create a new database named "test". await sys_db.create_database("test") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Create a new collection named "students". students = await db.create_collection("students") # Add a persistent index to the collection. await students.add_index(type="persistent", fields=["name"], options={"unique": True}) # Insert new documents into the collection. await students.insert({"name": "jane", "age": 39}) await students.insert({"name": "josh", "age": 18}) await students.insert({"name": "judy", "age": 21}) # Execute an AQL query and iterate through the result cursor. cursor = await db.aql.execute("FOR doc IN students RETURN doc") async with cursor: student_names = [] async for doc in cursor: student_names.append(doc["name"]) ``` -------------------------------- ### Create User with UserInfo or Dict Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Demonstrates creating a new user using either a UserInfo object or a dictionary. Ensure the username is present to avoid ValueErrors. ```python await db.create_user(UserInfo(user="john", password="secret")) await db.create_user({"user":"john", "password":"secret"}) ``` -------------------------------- ### options_available() Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Retrieves a description of all available server options. This method returns a dictionary detailing the configurable options for the server. ```APIDOC ## options_available() ### Description Return a description of all available server options. ### Returns Server options description. ### Return type dict ### Raises [**ServerAvailableOptionsGetError**](errors.md#arangoasync.exceptions.ServerAvailableOptionsGetError) – If the operation fails. ``` -------------------------------- ### Manage ArangoDB Databases with Python Async Source: https://github.com/arangodb/python-arango-async/blob/main/docs/database.md This snippet demonstrates how to initialize the ArangoClient, connect to the _system database, list all databases, create a new database, delete a database, create a database with new users, connect to a specific database as a user, update user permissions, retrieve database information, and execute custom requests. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth from arangoasync.request import Method, Request # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "_system" database as root user. sys_db = await client.db("_system", auth=auth) # List all databases. await sys_db.databases() # Create a new database named "test" if it does not exist. # Only root user has access to it at time of its creation. if not await sys_db.has_database("test"): await sys_db.create_database("test") # Delete the database. await sys_db.delete_database("test") # Create a new database named "test" along with a new set of users. # Only "jane", "john", "jake" and root user have access to it. if not await sys_db.has_database("test"): await sys_db.create_database( name="test", users=[ {"username": "jane", "password": "foo", "active": True}, {"username": "john", "password": "bar", "active": True}, {"username": "jake", "password": "baz", "active": True}, ], ) # Connect to the new "test" database as user "jane". db = await client.db("test", auth=Auth("jane", "foo")) # Make sure that user "jane" has read and write permissions. await sys_db.update_permission(username="jane", permission="rw", database="test") # Retrieve various database and server information. name = db.name version = await db.version() status = await db.status() collections = await db.collections() # Delete the database. Note that the new users will remain. await sys_db.delete_database("test") # Example of a custom request request = Request( method=Method.POST, endpoint="/_admin/execute", data="return 1".encode("utf-8") ) response = await sys_db.request(request) ``` -------------------------------- ### Get Structured Log Settings Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Retrieves the current structured log settings from the server. ```python db.log_settings() ``` -------------------------------- ### options() Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Retrieves the currently set server options. This method returns a dictionary containing the server's configuration options. ```APIDOC ## options() ### Description Return the currently-set server options. ### Returns Server options. ### Return type dict ### Raises [**ServerCurrentOptionsGetError**](errors.md#arangoasync.exceptions.ServerCurrentOptionsGetError) – If the operation fails. ``` -------------------------------- ### get Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Retrieves a document from the collection. Supports conditional retrieval based on revision and cluster read options. ```APIDOC ## async get(document, allow_dirty_read=False, if_match=None, if_none_match=None) ### Description Returns a document from the collection. Supports conditional retrieval based on revision and cluster read options. ### Parameters #### Path Parameters * **document** (str | dict) - Required - Document ID, key or body. Document body must contain the "_id" or "_key" field. * **allow_dirty_read** (bool) - Optional - Allow reads from followers in a cluster. * **if_match** (str | None) - Optional - The document is returned, if it has the same revision as the given ETag. * **if_none_match** (str | None) - Optional - The document is returned, if it has a different revision than the given ETag. ### Returns Document or None if not found. ### Raises * DocumentRevisionError: If the revision is incorrect. * DocumentGetError: If retrieval fails. * DocumentParseError: If the document is malformed. ``` -------------------------------- ### Initialize ArangoDB Client and Connect to Database Source: https://github.com/arangodb/python-arango-async/blob/main/docs/document.md Establishes a connection to the ArangoDB server and selects a specific database. Ensure the ArangoDB server is running and accessible at the specified host. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) ``` -------------------------------- ### Deploy Foxx Services from Local Files with Python Source: https://github.com/arangodb/python-arango-async/blob/main/docs/foxx.md This snippet shows how to create and replace Foxx services using local files, employing multipart/form-data and raw data uploads. It requires the aiohttp and aiofiles libraries for handling file uploads and asynchronous file operations. ```python import aiofiles import aiohttp import json from arangoasync import ArangoClient from arangoasync.auth import Auth # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "test" database as root user. db = await client.db("test", auth=auth) # Get the Foxx API wrapper. foxx = db.foxx # Define the test mount points. mount_point = "/test_mount" # Create the service using multipart/form-data. service = aiohttp.FormData() service.add_field( "source", open("./tests/static/service.zip", "rb"), filename="service.zip", content_type="application/zip", ) service.add_field("configuration", json.dumps({{}})) service.add_field("dependencies", json.dumps({{}})) service_info = await db.foxx.create_service( mount=mount_point, service=service, headers={"content-type": "multipart/form-data"} ) # Replace the service using raw data. async with aiofiles.open("./tests/static/service.zip", mode="rb") as f: service = await f.read() service_info = await db.foxx.replace_service( mount=mount_point, service=service, headers={"content-type": "application/zip"} ) # Delete the service. await db.foxx.delete_service(mount_point) ``` -------------------------------- ### Get API Calls Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Fetches a list of the most recent requests made to the server, including timestamps and endpoints. ```python db.api_calls() ``` -------------------------------- ### Get Server Status (Synchronous) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/migration.md Retrieves server status using the synchronous python-arango driver, expecting snake_case keys. ```python status = db.status() assert "host" in status assert "operation_mode" in status ``` -------------------------------- ### Initialize Client and Connect to _system DB Source: https://github.com/arangodb/python-arango-async/blob/main/docs/admin.md Initializes the ArangoDB client and connects to the `_system` database with root credentials. This is the entry point for most server administration tasks. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth # Initialize the client for ArangoDB. async with ArangoClient(hosts="http://localhost:8529") as client: auth = Auth(username="root", password="passwd") # Connect to "_system" database as root user. sys_db = await client.db("_system", auth=auth) ``` -------------------------------- ### Get Server Metrics Source: https://github.com/arangodb/python-arango-async/blob/main/docs/admin.md Retrieves server metrics in Prometheus format. This is valuable for monitoring the performance and health of the ArangoDB instance. ```python # Get metrics in Prometheus format metrics = await db.metrics() ``` -------------------------------- ### Basic Client-Side HTTPS with Default Settings Source: https://github.com/arangodb/python-arango-async/blob/main/docs/certificates.md Create a secure-by-default client context that verifies server certificates against the OS trust store and checks hostnames. This is the recommended approach for most use cases. ```python from arangoasync import ArangoClient from arangoasync.auth import Auth from arangoasync.http import DefaultHTTPClient import ssl # Create a default client context. ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) http_client = DefaultHTTPClient(ssl_context=ssl_ctx) # Initialize the client for ArangoDB. client = ArangoClient( hosts="https://localhost:8529", http_client=http_client, ) ``` -------------------------------- ### Build Documentation Source: https://github.com/arangodb/python-arango-async/blob/main/CONTRIBUTING.md Builds the project's documentation using Sphinx. The output can be found in the 'docs/_build' directory. ```shell python -m sphinx docs docs/_build # Open docs/_build/index.html in your browser ``` -------------------------------- ### Get and Reload TLS Data Source: https://github.com/arangodb/python-arango-async/blob/main/docs/certificates.md Retrieve current TLS configuration data from ArangoDB and reload it. This is useful for dynamic configuration changes. ```python async with ArangoClient(hosts=url) as client: db = await client.db( sys_db_name, auth_method="superuser", token=token, verify=True ) # Get TLS data tls = await db.tls() # Reload TLS data tls = await db.reload_tls() ``` -------------------------------- ### explain Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Provides the execution plan metadata for an AQL query without actually running it. It can also accept bind variables and custom options for the explanation. ```APIDOC ## async explain(query, bind_vars=None, options=None) ### Description Inspect the query and return its metadata without executing it. Accepts the query string, optional bind variables, and optional query execution options. ### Parameters #### Request Body - **query** (str) - Required - Query string to be explained. - **bind_vars** (dict | None) - Optional - An object with key/value pairs representing the bind parameters. - **options** (QueryExplainOptions | dict | None) - Optional - Extra options for the query. ``` -------------------------------- ### Customize Data Representation with a Formatter Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md Shows how to use a custom formatter function to transform the keys of a JsonWrapper object, for example, converting them to uppercase. ```python from arangoasync.typings import Json, UserInfo data = { "user": "john", "password": "secret", "active": True, "extra": {"role": "admin"}, } user_info = UserInfo(**data) def uppercase_formatter(data: Json) -> Json: result: Json = {} for key, value in data.items(): result[key.upper()] = value return result print(user_info.format(uppercase_formatter)) ``` -------------------------------- ### async shards(details=None) Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Returns collection shards and properties. Available only in a cluster setup. Includes responsible servers if details is set to True. ```APIDOC ## async shards(details=None) ### Description Returns collection shards and properties. This method is available only in a cluster setup. Optionally includes details about responsible servers. ### Method Asynchronous Python method call. ### Parameters #### Path Parameters None #### Query Parameters * **details** (bool | None) - If set to True, include responsible servers for these shards. #### Request Body None ### Returns Collection shards. ### Return type dict ### Raises * **CollectionShardsError** – If retrieval fails. ### References - [get-the-shard-ids-of-a-collection](https://docs.arango.ai/arangodb/stable/develop/http-api/collections/#get-the-shard-ids-of-a-collection) ``` -------------------------------- ### Initialize Client with Default Compression Source: https://github.com/arangodb/python-arango-async/blob/main/docs/compression.md Instantiate the ArangoClient with the DefaultCompressionManager to enable compression by default. ```python from arangoasync import ArangoClient from arangoasync.compression import DefaultCompressionManager client = ArangoClient( hosts="http://localhost:8529", compression=DefaultCompressionManager(), ) ``` -------------------------------- ### services Source: https://github.com/arangodb/python-arango-async/blob/main/docs/specs.md Lists all installed Foxx services, with an option to exclude system services. Note that Foxx microservice features are no longer available in ArangoDB 4.0. ```APIDOC ## async services(exclude_system=False) ### Description List installed Foxx services. System services can be optionally excluded. Note: Foxx microservice features are no longer available in ArangoDB 4.0. ### Parameters #### Query Parameters - **exclude_system** (bool | None) - Exclude system services. ### Response #### Success Response - **list** - List of installed services. ### Raises - **FoxxServiceListError** - If retrieval fails. ``` -------------------------------- ### Index Properties Example Source: https://github.com/arangodb/python-arango-async/blob/main/docs/helpers.md This JSON object outlines the properties of an ArangoDB index. It specifies the fields, ID, name, selectivity, sparsity, and type of the index. ```json { "fields" : [ "_key" ], "id" : "products/0", "name" : "primary", "selectivityEstimate" : 1, "sparse" : false, "type" : "primary", "unique" : true } ``` -------------------------------- ### Example JSON Document Structure Source: https://github.com/arangodb/python-arango-async/blob/main/docs/document.md Illustrates the structure of a standard JSON document within an ArangoDB collection, including unique identifiers and nested data. ```json { "_id": "students/bruce", "_key": "bruce", "_rev": "_Wm3dzEi--_", "first_name": "Bruce", "last_name": "Wayne", "address": { "street" : "1007 Mountain Dr.", "city": "Gotham", "state": "NJ" }, "is_rich": true, "friends": ["robin", "gordon"] } ``` -------------------------------- ### Example Graph JSON Data Source: https://github.com/arangodb/python-arango-async/wiki/demo/static/index.html This JSON structure defines a graph with nodes and edges. It is used for uploading and visualizing graph data in the ArangoDB demo. ```json { "name": "demo_star", "nodes": [ {"_key": "X"}, {"_key": "A"}, {"_key": "B"} {"_key": "C"}, {"_key": "D"}, {"_key": "E"} ], "edges": [ {"_from": "X", "_to": "A"}, {"_from": "X", "_to": "B"}, {"_from": "X", "_to": "C"}, {"_from": "X", "_to": "D"}, {"_from": "X", "_to": "E"}, {"_from": "A", "_to": "B"}, {"_from": "B", "_to": "C"}, {"_from": "D", "_to": "E"} ] } ```