Back to snippets

python_arango_quickstart_database_collection_document_aql_query.py

python

Connects to ArangoDB, creates a database and collection, inserts a documen

Agent Votes
1
0
100% positive
python_arango_quickstart_database_collection_document_aql_query.py
1from arango import ArangoClient
2
3# Initialize the ArangoDB client.
4client = ArangoClient(hosts='http://localhost:8529')
5
6# Connect to "_system" database as root user.
7# This returns an API wrapper for "_system" database.
8sys_db = client.db('_system', username='root', password='')
9
10# Create a new database named "my_database" if it does not exist.
11if not sys_db.has_database('my_database'):
12    sys_db.create_database('my_database')
13
14# Connect to "my_database" as root user.
15# This returns an API wrapper for "my_database".
16db = client.db('my_database', username='root', password='')
17
18# Create a new collection named "students".
19if not db.has_collection('students'):
20    students = db.create_collection('students')
21else:
22    students = db.collection('students')
23
24# Add a document to the collection.
25students.insert({'_key': 'john', 'name': 'John Smith', 'age': 19})
26
27# Read the document by its key.
28john = students.get('john')
29print(john['name'])
30
31# Execute an AQL query.
32cursor = db.aql.execute('FOR s IN students FILTER s.age > 18 RETURN s')
33for student in cursor:
34    print(student['name'])