how to insert data with variables in arangodb with python-arango

868 Views Asked by At

I try to insert data from a variable and can't find a way to do this, can someone help me? something like this:

name = "mark"
surname = "clark"

db.collection('user').insert([{'username': @name, 'usersurname': @surname}])

thanks!

2

There are 2 best solutions below

0
On

Your usage of @name and @surname is correct. What is missing is a call to a bind_vars dictionary in the AQL method. This will map the @ variables to their python variable values.

Here is your code using an alternative syntax. You will notice that I took the liberty to declare a collection variable as well; why not?

name = "mark"
surname = "clark"
collection = "user"

bind = {"@collection": collection, "name": name, "surname": surname}
aql = "INSERT {username: @name, usersurname: @surname} INTO @@collection"
query = db.aql.execute(aql, bind_vars=bind)

Note the single @ in front of variable names, but @@ in front of a collection name. In the bind dictionary, 0 and 1 @, respectively.

2
On

The "db.collection.insert" function is intended to work with objects/arrays, and does not support "variables" as such. In this case, you would use some sort of loop:

list_of_persons = [ {name: 'mark', surname: 'clark'} ]
for p in list_of_persons:
    db.collection('user').insert({'username': p.name, 'usersurname': p.surname})

Since variables are an AQL construct, they only supported in the query/cursor interface. Here you can specify the variable in the AQL (like @myVar) and specify a "bind variable" in the body of the call. You will have to read the docs for specific implementation, as they all differ slightly.