Table of Contents

Introduction 1.1

Official Drivers

Java Driver 2.1

Getting Started 2.1.1

Reference 2.1.2

Driver Setup 2.1.2.1

Database 2.1.2.2

Database Manipulation 2.1.2.2.1

Collection Access 2.1.2.2.2

View Access 2.1.2.2.3

Queries 2.1.2.2.4

AQL User Functions 2.1.2.2.5

Transactions 2.1.2.2.6

Graph Access 2.1.2.2.7

HTTP Routes 2.1.2.2.8

Collection 2.1.2.3

Collection Manipulation 2.1.2.3.1

Document Manipulation 2.1.2.3.2

Indexes 2.1.2.3.3

Bulk Import 2.1.2.3.4

View 2.1.2.4

View Manipulation 2.1.2.4.1

ArangoSearch Views 2.1.2.4.2

Cursor 2.1.2.5

Graph 2.1.2.6

Vertex Collection 2.1.2.6.1

Edge Collection 2.1.2.6.2

Vertices Manipulation 2.1.2.6.3

Edges Manipulation 2.1.2.6.4

Route 2.1.2.7

Serialization 2.1.2.8

ArangoJS - JavaScript Driver 2.2

Getting Started 2.2.1

Reference 2.2.2

Database 2.2.2.1

Database Manipulation 2.2.2.1.1

Collection Access 2.2.2.1.2

View Access 2.2.2.1.3

Queries 2.2.2.1.4

AQL User Functions 2.2.2.1.5

Transactions 2.2.2.1.6

Graph Access 2.2.2.1.7

Foxx Services 2.2.2.1.8

HTTP Routes 2.2.2.1.9

Collection 2.2.2.2

Collection Manipulation 2.2.2.2.1

Document Manipulation 2.2.2.2.2

DocumentCollection 2.2.2.2.3

EdgeCollection 2.2.2.2.4

Indexes 2.2.2.2.5

Simple Queries 2.2.2.2.6

Bulk Import 2.2.2.2.7

View Manipulation 2.2.2.3

Cursor 2.2.2.4

Graph 2.2.2.5

Vertices 2.2.2.5.1

Edges 2.2.2.5.2

VertexCollection 2.2.2.5.3

EdgeCollection 2.2.2.5.4

Route 2.2.2.6

ArangoDB-PHP 2.3

Getting Started 2.3.1

Tutorial 2.3.2

ArangoDB Go Driver 2.4

Getting Started 2.4.1

Example Requests 2.4.2

Connection Management 2.4.3

Integrations

Spring Data ArangoDB 3.1

Getting Started 3.1.1

Reference 3.1.2

Template 3.1.2.1

Queries 3.1.2.1.1

Document Manipulation 3.1.2.1.2

Multiple Document Manipulation 3.1.2.1.3

Collection Manipulation 3.1.2.1.4

Repositories 3.1.2.2

Queries 3.1.2.2.1

Derived queries 3.1.2.2.1.1

Query methods 3.1.2.2.1.2

Named queries 3.1.2.2.1.3

Document Manipulation 3.1.2.2.2

Multiple Document Manipulation 3.1.2.2.3

Query by example 3.1.2.2.4

Mapping 3.1.2.3

Document 3.1.2.3.1

Edge 3.1.2.3.2

Reference 3.1.2.3.3

Relations 3.1.2.3.4

Indexes 3.1.2.3.5

Converter 3.1.2.3.6

Events 3.1.2.3.7

Migration 3.1.3

Migrating 1.x to 3.0 3.1.3.1

Migrating 2.x to 3.0 3.1.3.2

ArangoDB Spark Connector 4.1

Getting Started 4.1.1

Reference 4.1.2

Java 4.1.2.1

Scala 4.1.2.2

Introduction

ArangoDB v3.4.devel 08. Sep 2018 Drivers Documentation

Official drivers

Name | Language | Repository |
ArangoDB-Java-Driver | Java | https://github.com/arangodb/arangodb-java-driver | Changelog
ArangoDB-Java-Driver-Async | Java | https://github.com/arangodb/arangodb-java-driver-async | Changelog
ArangoJS | JavaScript | https://github.com/arangodb/arangojs | Changelog
ArangoDB-PHP | PHP | https://github.com/arangodb/arangodb-php | Changelog
Go-Driver | Go | https://github.com/arangodb/go-driver | Changelog

Integrations

Name | Language | Repository |
Spring Data | Java | https://github.com/arangodb/spring-data | Changelog
ArangoDB-Spark-Connector | Scala, Java | https://github.com/arangodb/arangodb-spark-connector | Changelog

Community drivers

Please note that this list is not exhaustive.

Name | Language | Repository
ArangoDB-PHP-Core | PHP | https://github.com/frankmayer/ArangoDB-PHP-Core
ArangoDB-NET | .NET | https://github.com/yojimbo87/ArangoDB-NET
aranGO | Go | https://github.com/diegogub/aranGO
arangolite | Go | https://github.com/solher/arangolite
aranGoDriver | Go | https://github.com/TobiEiss/aranGoDriver
pyArango | Python | http://www.github.com/tariqdaouda/pyArango
python-arango | Python | https://github.com/Joowani/python-arango
Scarango | Scala | https://github.com/outr/scarango
ArangoRB | Ruby | https://github.com/StefanoMartin/ArangoRB

Java Driver

ArangoDB Java Driver

The official ArangoDB Java Driver.

Getting Started

Reference

See Also

ChangeLog

Examples

Tutorial

JavaDoc

JavaDoc VelocyPack

Getting Started

ArangoDB Java Driver - Getting Started

Supported versions

arangodb-java-driver | ArangoDB | network protocol | Java version
4.2.x+ | 3.0.0+ | VelocyStream, HTTP | 1.6+
4.1.x | 3.1.0+ | VelocyStream | 1.6+
3.1.x | 3.1.0+ | HTTP | 1.6+
3.0.x | 3.0.x | HTTP | 1.6+
2.7.4 | 2.7.x, 2.8.x | HTTP | 1.6+

Note: VelocyStream is only supported in ArangoDB 3.1 and above.

Maven

To add the driver to your project with maven, add the following code to your pom.xml (please use a driver with a version number compatible to your ArangoDB server's version):

ArangoDB 3.x.x

<dependencies>
  <dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>arangodb-java-driver</artifactId>
    <version>4.6.0</version>
  </dependency>
</dependencies>

If you want to test with a snapshot version (e.g. 4.6.0-SNAPSHOT), add the staging repository of oss.sonatype.org to your pom.xml:

<repositories>
  <repository>
    <id>arangodb-snapshots</id>
    <url>https://oss.sonatype.org/content/groups/staging</url>
  </repository>
</repositories>

Compile the Java Driver

mvn clean install -DskipTests=true -Dgpg.skip=true -Dmaven.javadoc.skip=true -B

Reference

ArangoDB Java Driver - Reference

Driver Setup

Database

Database Manipulation

Collection Access

View Access

Queries

AQL User Functions

Transactions

Graph Access

HTTP Routes

Collection

Collection Manipulation

Document Manipulation

Indexes

Bulk Import

View

View Manipulation

ArangoSearch Views

Cursor

Graph

Vertex Collection

Edge Collection

Vertices Manipulation

Edges Manipulation

Route

Serialization

Driver Setup

Driver setup

Setup with default configuration, this automatically loads a properties file arangodb.properties if exists in the classpath:

  // this instance is thread-safe
  ArangoDB arangoDB = new ArangoDB.Builder().build();

The driver is configured with some default values:

property-key | description | default value
arangodb.hosts | ArangoDB hosts | 127.0.0.1:8529
arangodb.timeout | socket connect timeout(millisecond) | 0
arangodb.user | Basic Authentication User |
arangodb.password | Basic Authentication Password |
arangodb.useSsl | use SSL connection | false
arangodb.chunksize | VelocyStream Chunk content-size(bytes) | 30000
arangodb.connections.max | max number of connections | 1 VST, 20 HTTP
arangodb.protocol | used network protocol | VST

To customize the configuration the parameters can be changed in the code...

  ArangoDB arangoDB = new ArangoDB.Builder().host("192.168.182.50", 8888).build();

... or with a custom properties file (my.properties)

  InputStream in = MyClass.class.getResourceAsStream("my.properties");
  ArangoDB arangoDB = new ArangoDB.Builder().loadProperties(in).build();

Example for arangodb.properties:

  arangodb.hosts=127.0.0.1:8529,127.0.0.1:8529
  arangodb.user=root
  arangodb.password=

Network protocol

The drivers default used network protocol is the binary protocol VelocyStream which offers the best performance within the driver. To use HTTP, you have to set the configuration useProtocol to Protocol.HTTP_JSON for HTTP with Json content or Protocol.HTTP_VPACK for HTTP with VelocyPack content.

  ArangoDB arangoDB = new ArangoDB.Builder().useProtocol(Protocol.VST).build();

In addition to set the configuration for HTTP you have to add the apache httpclient to your classpath.

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.1</version>
</dependency>

Note: If you are using ArangoDB 3.0.x you have to set the protocol to Protocol.HTTP_JSON because it is the only one supported.

SSL

To use SSL, you have to set the configuration useSsl to true and set a SSLContext (see example code).

  ArangoDB arangoDB = new ArangoDB.Builder().useSsl(true).sslContext(sc).build();

Connection Pooling

The driver supports connection pooling for VelocyStream with a default of 1 and HTTP with a default of 20 maximum connections. To change this value use the method maxConnections(Integer) in ArangoDB.Builder.

  ArangoDB arangoDB = new ArangoDB.Builder().maxConnections(8).build();

The driver does not explicitly release connections. To avoid exhaustion of resources when no connection is needed, you can clear the connection pool (close all connections to the server) or use connection TTL.

arangoDB.shutdown();

Fallback hosts

The driver supports configuring multiple hosts. The first host is used to open a connection to. When this host is not reachable the next host from the list is used. To use this feature just call the method host(String, int) multiple times.

  ArangoDB arangoDB = new ArangoDB.Builder().host("host1", 8529).host("host2", 8529).build();

Since version 4.3 the driver support acquiring a list of known hosts in a cluster setup or a single server setup with followers. For this the driver has to be able to successfully open a connection to at least one host to get the list of hosts. Then it can use this list when fallback is needed. To use this feature just pass true to the method acquireHostList(boolean).

  ArangoDB arangoDB = new ArangoDB.Builder().acquireHostList(true).build();

Load Balancing

Since version 4.3 the driver supports load balancing for cluster setups in two different ways.

The first one is a round robin load balancing where the driver iterates through a list of known hosts and performs every request on a different host than the request before. This load balancing strategy only work when the maximun of connections is greater 1.

  ArangoDB arangoDB = new ArangoDB.Builder().loadBalancingStrategy(LoadBalancingStrategy.ROUND_ROBIN).maxConnections(8).build();

Just like the Fallback hosts feature the round robin load balancing strategy can use the acquireHostList configuration to acquire a list of all known hosts in the cluster. Do so only requires the manually configuration of only one host. Because this list is updated frequently it makes load balancing over the whole cluster very comfortable.

  ArangoDB arangoDB = new ArangoDB.Builder().loadBalancingStrategy(LoadBalancingStrategy.ROUND_ROBIN).maxConnections(8).acquireHostList(true).build();

The second load balancing strategy allows to pick a random host from the configured or acquired list of hosts and sticks to that host as long as the connection is open. This strategy is useful for an application - using the driver - which provides a session management where each session has its own instance of ArangoDB build from a global configured list of hosts. In this case it could be wanted that every sessions sticks with all its requests to the same host but not all sessions should use the same host. This load balancing strategy also works together with acquireHostList.

  ArangoDB arangoDB = new ArangoDB.Builder().loadBalancingStrategy(LoadBalancingStrategy.ONE_RANDOM).acquireHostList(true).build();

Connection time to live

Since version 4.4 the driver supports setting a TTL for connections managed by the internal connection pool. Setting a TTL helps when using load balancing strategy ROUND_ROBIN, because as soon as a coordinator goes down, every open connection to that host will be closed and opened again with another target coordinator. As long as the driver does not have to open new connections (all connections in the pool are used) it will use only the coordinators which never went down. To use the downed coordinator again, when it is running again, the connections in the connection pool have to be closed and opened again with the target host mentioned by the load balancing strategy. To achieve this you can manually call ArangoDB.shutdown in your client code or use the TTL for connection so that a downed coordinator (which is then brought up again) will be used again after a certain time.

ArangoDB arango = new ArangoDB.Builder().connectionTtl(5 * 60 * 1000).build();

In this example all connections will be closed/reopened after 5 minutes.

Connection TTL can be disabled setting it to null:

.connectionTtl(null)

The default TTL is null (no automatic connection closure).

Database

Database API

ArangoDB.db

ArangoDB.db(String name) : ArangoDatabase

Returns a ArangoDatabase instance for the given database name.

Arguments

name: String

Name of the database

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

Database Manipulation

Manipulation databases

These functions implement the HTTP API for manipulating databases.

ArangoDB.createDatabase

ArangoDB.createDatabase(String name) : Boolean

Creates a new database with the given name.

Arguments

name: String

Name of the database to create

Examples

ArangoDB arango = new ArangoDB.Builder().build();
arango.createDatabase("myDB");

ArangoDatabase.create()

ArangoDatabase.create() : Boolean

Creates the database.

Alternative for ArangoDB.createDatabase.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.create();

ArangoDatabase.exists()

ArangoDatabase.exists() : boolean

Checks whether the database exists

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
boolean exists = db.exists();

ArangoDatabase.getInfo

ArangoDatabase.getInfo() : DatabaseEntity

Retrieves information about the current database

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
DatabaseEntity info = db.getInfo();

ArangoDB.getDatabases

ArangoDB.getDatabases() : Collection<String>

Retrieves a list of all existing databases

Examples

ArangoDB arango = new ArangoDB.Builder().build();
Collection<String> names = arango.getDatabases();

ArangoDatabase.drop

ArangoDatabase.drop() : Boolean

Deletes the database from the server.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.drop();

Collection Access

Accessing collections

These functions implement the HTTP API for accessing collections.

ArangoDatabase.collection

ArangoDatabase.collection(String name) : ArangoCollection

Returns a ArangoCollection instance for the given collection name.

Arguments

name: String

Name of the collection

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("myCollection");

ArangoDatabase.getCollections

ArangoDatabase.getCollections() : Collection<CollectionEntity>

Fetches all collections from the database and returns an list of collection descriptions.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
Collection<CollectionEntity> infos = db.getCollections();

View Access

Accessing views

These functions implement the HTTP API for accessing view.

ArangoDatabase.view

ArangoDatabase.view(String name) : ArangoView

Returns a ArangoView instance for the given view name.

Arguments

name: String

Name of the view

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoView view = db.view("myView");

ArangoDatabase.arangoSearch

ArangoDatabase.arangoSearch(String name) : ArangoSearch

Returns a ArangoSearch instance for the given ArangoSearch View name.

Arguments

name: String

Name of the view

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoSearch view = db.arangoSearch("myArangoSearchView");

ArangoDatabase.getViews

ArangoDatabase.getViews() : Collection<ViewEntity>

Fetches all views from the database and returns an list of collection descriptions.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
Collection<ViewEntity> infos = db.getViews();

Queries

Queries

This function implements the HTTP API for single roundtrip AQL queries.

ArangoDatabase.query

ArangoDatabase.query(String query, Map<String, Object> bindVars, AqlQueryOptions options, Class<T> type) : ArangoCursor<T>

Performs a database query using the given query and bindVars, then returns a new ArangoCursor instance for the result list.

Arguments

query: String

An AQL query string

bindVars: Map<String, Object>

key/value pairs defining the variables to bind the query to

options: AqlQueryOptions

count: Boolean

Indicates whether the number of documents in the result set should be returned in the "count" attribute of the result. Calculating the "count" attribute might have a performance impact for some queries in the future so this option is turned off by default, and "count" is only returned when requested.

ttl: Integer

The time-to-live for the cursor (in seconds). The cursor will be removed on the server automatically after the specified amount of time. This is useful to ensure garbage collection of cursors that are not fully fetched by clients. If not set, a server-defined value will be used.

batchSize: Integer

Maximum number of result documents to be transferred from the server to the client in one roundtrip. If this attribute is not set, a server-controlled default value will be used. A batchSize value of 0 is disallowed.

memoryLimit: Long

The maximum number of memory (measured in bytes) that the query is allowed to use. If set, then the query will fail with error "resource limit exceeded" in case it allocates too much memory. A value of 0 indicates that there is no memory limit.

cache: Boolean

Flag to determine whether the AQL query cache shall be used. If set to false, then any query cache lookup will be skipped for the query. If set to true, it will lead to the query cache being checked for the query if the query cache mode is either on or demand.

failOnWarning: Boolean

When set to true, the query will throw an exception and abort instead of producing a warning. This option should be used during development to catch potential issues early. When the attribute is set to false, warnings will not be propagated to exceptions and will be returned with the query result. There is also a server configuration option --query.fail-on-warning for setting the default value for failOnWarning so it does not need to be set on a per-query level.

profile: Boolean

If set to true, then the additional query profiling information will be returned in the sub-attribute profile of the extra return attribute if the query result is not served from the query cache.

maxTransactionSize: Long

Transaction size limit in bytes. Honored by the RocksDB storage engine only.

maxWarningCount: Long

Limits the maximum number of warnings a query will return. The number of warnings a query will return is limited to 10 by default, but that number can be increased or decreased by setting this attribute.

intermediateCommitCount: Long

Maximum number of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

intermediateCommitSize: Long

Maximum total size of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

satelliteSyncWait: Double

This Enterprise Edition parameter allows to configure how long a DBServer will have time to bring the satellite collections involved in the query into sync. The default value is 60.0 (seconds). When the max time has been reached the query will be stopped.

skipInaccessibleCollections

AQL queries (especially graph traversals) will treat collection to which a user has no access rights as if these collections were empty. Instead of returning a forbidden access error, your queries will execute normally. This is intended to help with certain use-cases: A graph contains several collections and different users execute AQL queries on that graph. You can now naturally limit the accessible results by changing the access rights of users on collections. This feature is only available in the Enterprise Edition.

fullCount: Boolean

If set to true and the query contains a LIMIT clause, then the result will have an extra attribute with the sub-attributes stats and fullCount, { ... , "extra": { "stats": { "fullCount": 123 } } }. The fullCount attribute will contain the number of documents in the result before the last top-level LIMIT in the query was applied. It can be used to count the number of documents that match certain filter criteria, but only return a subset of them, in one go. It is thus similar to MySQL's SQL_CALC_FOUND_ROWS hint. Note that setting the option will disable a few LIMIT optimizations and may lead to more documents being processed, and thus make queries run longer. Note that the fullCount attribute may only be present in the result if the query has a top-level LIMIT clause and the LIMIT clause is actually used in the query.

maxPlans: Integer

Limits the maximum number of plans that are created by the AQL query optimizer.

rules: Collection<String>

A list of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling the optimizer to include or exclude specific rules. To disable a rule, prefix its name with a -, to enable a rule, prefix it with a +. There is also a pseudo-rule all, which will match all optimizer rules.

stream: Boolean

Specify true and the query will be executed in a streaming fashion. The query result is not stored on the server, but calculated on the fly. Beware: long-running queries will need to hold the collection locks for as long as the query cursor exists. When set to false a query will be executed right away in its entirety. In that case query results are either returned right away (if the resultset is small enough), or stored on the arangod instance and accessible via the cursor API (with respect to the ttl). It is advisable to only use this option on short-running queries or without exclusive locks (write-locks on MMFiles). Please note that the query options cache, count and fullCount will not work on streaming queries. Additionally query statistics, warnings and profiling data will only be available after the query is finished. The default value is false.

type: Class<T>

The type of the result (POJO class, VPackSlice, String for Json, or Collection/List/Map)

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCursor<BaseDocument> cursor = db.query("FOR i IN @@collection RETURN i"
                                             new MapBuilder().put("@collection", "myCollection").get(),
                                             new AqlQueryOptions(),
                                             BaseDocument.class);

AQL User Functions

Managing AQL user functions

These functions implement the HTTP API for managing AQL user functions.

ArangoDatabase.getAqlFunctions

ArangoDatabase.getAqlFunctions(AqlFunctionGetOptions options) : Collection<AqlFunctionEntity>

Arguments

options: AqlFunctionGetOptions

namespace: String

Returns all registered AQL user functions from namespace namespace

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
Collection<AqlFunctionEntity> functions = db.getAqlFunctions(new AqlFunctionGetOptions().namespace("myfuncs"));
// functions is a list of function descriptions

ArangoDatabase.createAqlFunction

ArangoDatabase.createAqlFunction(String name, String code, AqlFunctionCreateOptions options) : void

Arguments

name: String

A valid AQL function name, e.g.: "myfuncs::accounting::calculate_vat"

code: String

A String evaluating to a JavaScript function

options: AqlFunctionCreateOptions

isDeterministic: Boolean

An optional boolean value to indicate that the function results are fully deterministic (function return value solely depends on the input value and return value is the same for repeated calls with same input)

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.createAqlFunction("ACME::ACCOUNTING::CALCULATE_VAT",
                     "function (price) { return 0.19; }",
                     new AqlFunctionCreateOptions());
// Use the new function in an AQL query
String query = "FOR product IN products"
               + "RETURN MERGE("
               + "{vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price)}, product)";
ArangoCursor<Double> cursor = db.query(query, null, new AqlQueryOptions(), Double.class);
// cursor is a cursor for the query result

ArangoDatabase.deleteAqlFunction

ArangoDatabase.deleteAqlFunction(String name, AqlFunctionDeleteOptions options): Integer

Deletes the AQL user function with the given name from the database.

Arguments

name: String

The name of the user function to delete

options: AqlFunctionDeleteOptions

group: Boolean

If set to true, then the function name provided in name is treated as a namespace prefix, and all functions in the specified namespace will be deleted. If set to false, the function name provided in name must be fully qualified, including any namespaces.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.deleteAqlFunction("ACME::ACCOUNTING::CALCULATE_VAT", new AqlFunctionDeleteOptions());
// the function no longer exists

Transactions

Transactions

This function implements the HTTP API for transactions.

ArangoDatabase.transaction

ArangoDatabase.transaction(String action, Class<T> type, TransactionOptions options) : T

Performs a server-side transaction and returns its return value.

Arguments

action: String

A String evaluating to a JavaScript function to be executed on the server.

type: Class

The type of the result (POJO class, VPackSlice or String for Json)

options: TransactionOptions

Additional transaction options

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
String action = "function (params) {"
                + "const db = require('@arangodb').db;"
                + "return db._query('FOR i IN test RETURN i._key').toArray();"
              + "}";
String[] keys = arango.db().transaction(action, String[].class, new TransactionOptions());

Graph Access

Accessing graphs

These functions implement the HTTP API for accessing general graphs.

ArangoDatabase.graph

ArangoDatabase.graph(String name) : ArangoGraph

Returns a ArangoGraph instance for the given graph name.

Arguments

name: String

Name of the graph

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("myGraph");

HTTP Routes

Arbitrary HTTP routes

ArangoDatabase.route

ArangoDatabase.route(String... path) : ArangoRoute

Returns a new ArangoRoute instance for the given path (relative to the database) that can be used to perform arbitrary requests.

Arguments

path: String...

The database-relative URL of the route

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoRoute myFoxxService = db.route("my-foxx-service");

VPackSlice body = arango.util().serialize("{'username': 'admin', 'password': 'hunter2'");
Response response = myFoxxService.route("users").withBody(body).post();
// response.getBody() is the result of
// POST /_db/myDB/my-foxx-service/users
// with VelocyPack request body '{"username": "admin", "password": "hunter2"}'

Collection

Collection API

These functions implement the HTTP API for collections.

The ArangoCollection API is used for all collections, regardless of their specific type (document/edge collection).

Getting information about the collection

See the HTTP API documentation for details.

ArangoCollection.exists

ArangoCollection.exists() : boolean

Checks whether the collection exists

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");

boolean exists = collection.exists();

ArangoCollection.getInfo

ArangoCollection.getInfo() : CollectionEntity

Returns information about the collection.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");

CollectionEntity info = collection.getInfo();

ArangoCollection.getProperties

ArangoCollection.getProperties() : CollectionPropertiesEntity

Reads the properties of the specified collection.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");

CollectionPropertiesEntity properties = collection.getProperties();

ArangoCollection.getRevision

ArangoCollection.getRevision() : CollectionRevisionEntity

Retrieve the collections revision.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");

CollectionRevisionEntity revision = collection.getRevision();

ArangoCollection.getIndexes

ArangoCollection.getIndexes() : Collection<IndexEntity>

Fetches a list of all indexes on this collection.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");

Collection<IndexEntity> indexes = collection.getIndexes();

Collection Manipulation

Manipulating the collection

These functions implement the HTTP API for modifying collections.

ArangoDatabase.createCollection

ArangoDatabase.createCollection(String name, CollectionCreateOptions options) : CollectionEntity

Creates a collection with the given options for this collection's name, then returns collection information from the server.

Arguments

name: String

The name of the collection

options: CollectionCreateOptions

journalSize: Long

The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MiB).

replicationFactor: Integer

(The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication between them is synchronous, that is, every write operation to the "leader" copy will be replicated to all "follower" replicas, before the write operation is reported successful. If a server fails, this is detected automatically and one of the servers holding copies take over, usually without an error being reported.

satellite: Boolean

If the true the collection is created as a satellite collection. In this case the replicationFactor is ignored.

waitForSync: Boolean

If true then the data is synchronized to disk before returning from a document create, update, replace or removal operation. (default: false)

doCompact: Boolean

Whether or not the collection will be compacted (default is true)

isVolatile: Boolean

If true then the collection data is kept in-memory only and not made persistent. Unloading the collection will cause the collection data to be discarded. Stopping or re-starting the server will also cause full loss of data in the collection. Setting this option will make the resulting collection be slightly faster than regular collections because ArangoDB does not enforce any synchronization to disk and does not calculate any CRC checksums for datafiles (as there are no datafiles). This option should therefore be used for cache-type collections only, and not for data that cannot be re-created otherwise. (The default is false)

shardKeys: String...

(The default is [ "_key" ]): in a cluster, this attribute determines which document attributes are used to determine the target shard for documents. Documents are sent to shards based on the values of their shard key attributes. The values of all shard key attributes in a document are hashed, and the hash value is used to determine the target shard. Note: Values of shard key attributes cannot be changed once set. This option is meaningless in a single server setup.

numberOfShards: Integer

(The default is 1): in a cluster, this value determines the number of shards to create for the collection. In a single server setup, this option is meaningless.

isSystem: Boolean

If true, create a system collection. In this case collection-name should start with an underscore. End users should normally create non-system collections only. API implementors may be required to create system collections in very special occasions, but normally a regular collection will do. (The default is false)

type: CollectionType

(The default is CollectionType#DOCUMENT): the type of the collection to create.

indexBuckets: Integer

The: number of buckets into which indexes using a hash table are split. The default is 16 and this number has to be a power of 2 and less than or equal to 1024. For very large collections one should increase this to avoid long pauses when the hash table has to be initially built or resized, since buckets are resized individually and can be initially built in parallel. For example, 64 might be a sensible value for a collection with 100 000 000 documents. Currently, only the edge index respects this value, but other index types might follow in future ArangoDB versions. Changes (see below) are applied when the collection is loaded the next time.

distributeShardsLike: String

(The default is ""): in an Enterprise Edition cluster, this attribute binds the specifics of sharding for the newly created collection to follow that of a specified existing collection. Note: Using this parameter has consequences for the prototype collection. It can no longer be dropped, before sharding imitating collections are dropped. Equally, backups and restores of imitating collections alone will generate warnings, which can be overridden, about missing sharding prototype.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.createCollection("potatoes", new CollectionCreateOptions());
// the document collection "potatoes" now exists

ArangoCollection.create

ArangoCollection.create(CollectionCreateOptions options) : CollectionEntity

Creates a collection with the given options for this collection's name, then returns collection information from the server.

Alternative for ArangoDatabase.createCollection.

Arguments

options: CollectionCreateOptions

journalSize: Long

The maximal size of a journal or datafile in bytes. The value must be at least 1048576 (1 MiB).

replicationFactor: Integer

(The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication between them is synchronous, that is, every write operation to the "leader" copy will be replicated to all "follower" replicas, before the write operation is reported successful. If a server fails, this is detected automatically and one of the servers holding copies take over, usually without an error being reported.

satellite: Boolean

If the true the collection is created as a satellite collection. In this case the replicationFactor is ignored.

waitForSync: Boolean

If true then the data is synchronized to disk before returning from a document create, update, replace or removal operation. (default: false)

doCompact: Boolean

Whether or not the collection will be compacted (default is true)

isVolatile: Boolean

If true then the collection data is kept in-memory only and not made persistent. Unloading the collection will cause the collection data to be discarded. Stopping or re-starting the server will also cause full loss of data in the collection. Setting this option will make the resulting collection be slightly faster than regular collections because ArangoDB does not enforce any synchronization to disk and does not calculate any CRC checksums for datafiles (as there are no datafiles). This option should therefore be used for cache-type collections only, and not for data that cannot be re-created otherwise. (The default is false)

shardKeys: String...

(The default is [ "_key" ]): in a cluster, this attribute determines which document attributes are used to determine the target shard for documents. Documents are sent to shards based on the values of their shard key attributes. The values of all shard key attributes in a document are hashed, and the hash value is used to determine the target shard. Note: Values of shard key attributes cannot be changed once set. This option is meaningless in a single server setup.

numberOfShards: Integer

(The default is 1): in a cluster, this value determines the number of shards to create for the collection. In a single server setup, this option is meaningless.

isSystem: Boolean

If true, create a system collection. In this case collection-name should start with an underscore. End users should normally create non-system collections only. API implementors may be required to create system collections in very special occasions, but normally a regular collection will do. (The default is false)

type: CollectionType

(The default is CollectionType#DOCUMENT): the type of the collection to create.

indexBuckets: Integer

The: number of buckets into which indexes using a hash table are split. The default is 16 and this number has to be a power of 2 and less than or equal to 1024. For very large collections one should increase this to avoid long pauses when the hash table has to be initially built or resized, since buckets are resized individually and can be initially built in parallel. For example, 64 might be a sensible value for a collection with 100 000 000 documents. Currently, only the edge index respects this value, but other index types might follow in future ArangoDB versions. Changes (see below) are applied when the collection is loaded the next time.

distributeShardsLike: String

(The default is ""): in an Enterprise Edition cluster, this attribute binds the specifics of sharding for the newly created collection to follow that of a specified existing collection. Note: Using this parameter has consequences for the prototype collection. It can no longer be dropped, before sharding imitating collections are dropped. Equally, backups and restores of imitating collections alone will generate warnings, which can be overridden, about missing sharding prototype.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("potatoes");
collection.create(new CollectionCreateOptions());
// the document collection "potatoes" now exists

ArangoCollection.load

ArangoCollection.load() : CollectionEntity

Tells the server to load the collection into memory.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");
collection.load();
// the collection has now been loaded into memory

ArangoCollection.unload

ArangoCollection.unload() : CollectionEntity

Tells the server to remove the collection from memory. This call does not delete any documents. You can use the collection afterwards; in which case it will be loaded into memory, again.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");
collection.unload();
// the collection has now been unloaded from memory

ArangoCollection.changeProperties

ArangoCollection.changeProperties(CollectionPropertiesOptions options) : CollectionPropertiesEntity

Changes the properties of the collection.

Arguments

options: CollectionPropertiesEntity

For information on the properties argument see the HTTP API for modifying collections.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

CollectionPropertiesEntity result = collection.changeProperties(new CollectionPropertiesEntity().waitForSync(true));
assertThat(result.getWaitForSync(), is(true));
// the collection will now wait for data being written to disk
// whenever a document is changed

ArangoCollection.rename

ArangoCollection.rename(String newName) : CollectionEntity

Renames the collection

Arguments

newName: String

The new name

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

CollectionEntity result = collection.rename("new-collection-name")
assertThat(result.getName(), is("new-collection-name");
// result contains additional information about the collection

ArangoCollection.truncate

ArangoCollection.truncate() : CollectionEntity

Removes all documents from the collection, but leaves the indexes intact.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

collection.truncate();
// the collection "some-collection" is now empty

ArangoCollection.drop

ArangoCollection.drop() : void

Deletes the collection from the database.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

collection.drop();
// the collection "some-collection" no longer exists

Document Manipulation

Manipulating documents

These functions implement the HTTP API for manipulating documents.

ArangoCollection.documentExists

ArangoCollection.documentExists(String key) : Boolean

Checks if the document exists by reading a single document head

Arguments

key: String

The key of the document

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

Boolean exists = collection.documentExists("some-key");

ArangoCollection.getDocument

ArangoCollection.getDocument(String key, Class<T> type, DocumentReadOptions options) : T

Retrieves the document with the given _key from the collection.

Arguments

key: String

The key of the document

type: Class<T>

The type of the document (POJO class, VPackSlice or String for Json)

options: DocumentReadOptions

ifNoneMatch: String

Document revision must not contain If-None-Match

ifMatch: String

Document revision must contain If-Match

catchException: Boolean

Whether or not catch possible thrown exceptions

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument document = collection.getDocument("some-key", BaseDocument.class);

ArangoCollection.getDocuments

ArangoCollection.getDocuments(Collection<String> keys, Class<T> type) : MultiDocumentEntity<T>

Retrieves multiple documents with the given _key from the collection.

Arguments

keys: Collection<String>

The key of the document

type: Class<T>

The type of the document (POJO class, VPackSlice or String for Json)

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

Collection<String> keys = Arrays.asList("some-key", "some-other-key");
MultiDocumentEntity<BaseDocument> documents = collection.getDocuments(keys, BaseDocument.class);

ArangoCollection.insertDocument

ArangoCollection.insertDocument(T value, DocumentCreateOptions options) : DocumentCreateEntity<T>

Creates a new document from the given document, unless there is already a document with the _key given. If no _key is given, a new unique _key is generated automatically.

Arguments

value: T

A representation of a single document (POJO, VPackSlice or String for Json)

options: DocumentCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

overwrite: Boolean

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument document = new BaseDocument();
document.addAttribute("some", "data");
collection.insertDocument(document, new DocumentCreateOptions());

ArangoCollection.insertDocuments

ArangoCollection.insertDocuments(Collection<T> values, DocumentCreateOptions options) : MultiDocumentEntity<DocumentCreateEntity<T>>

Creates new documents from the given documents, unless there is already a document with the _key given. If no _key is given, a new unique _key is generated automatically.

Arguments

values: Collection<T>

A List of documents (POJO, VPackSlice or String for Json)

options: DocumentCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

overwrite: Boolean

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument doc1 = new BaseDocument();
BaseDocument doc2 = new BaseDocument();
BaseDocument doc3 = new BaseDocument();
collection.insertDocuments(Arrays.asList(doc1, doc2, doc3), new DocumentCreateOptions());

ArangoCollection.replaceDocument

ArangoCollection.replaceDocument(String key, T value, DocumentReplaceOptions options) : DocumentUpdateEntity<T>

Replaces the document with key with the one in the body, provided there is such a document and no precondition is violated.

Arguments

key: String

The key of the document

value: T

A representation of a single document (POJO, VPackSlice or String for Json)

options: DocumentReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument document = new BaseDocument();
document.addAttribute("hello", "world");
DocumentCreateEntity<BaseDocument> info = collection.insertDocument(document);

document.addAttribute("hello", "world2");
collection.replaceDocument(info.getKey(), document, new DocumentReplaceOptions());

BaseDocument doc = collection.getDocument(info.getKey());
assertThat(doc.getAttribute("hello"), is("world2"));

ArangoCollection.replaceDocuments

ArangoCollection.replaceDocuments(Collection<T> values, DocumentReplaceOptions options) : MultiDocumentEntity<DocumentUpdateEntity<T>>

Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are specified by the _key attributes in the documents in values.

Arguments

values: Collection<T>

A List of documents (POJO, VPackSlice or String for Json)

options: DocumentReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument doc1 = new BaseDocument();
BaseDocument doc2 = new BaseDocument();
BaseDocument doc3 = new BaseDocument();
collection.insertDocuments(Arrays.asList(doc1, doc2, doc3));

// change values of doc1, doc2, doc3

collection.replaceDocuments(Arrays.asList(doc1, doc2, doc3), new DocumentReplaceOptions());

ArangoCollection.updateDocument

ArangoCollection.updateDocument(String key, T value, DocumentUpdateOptions options) : DocumentUpdateEntity<T>

Updates the document with key with the one in the body, provided there is such a document and no precondition is violated.

Arguments

key: String

The key of the document

value: T

A representation of a single document (POJO, VPackSlice or String for Json)

options: DocumentUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument document = new BaseDocument();
document.addAttribute("hello", "world");
DocumentCreateEntity<BaseDocument> info = collection.insertDocument(document);

document.addAttribute("hello", "world2");
collection.updateDocument(info.getKey(), document, new DocumentUpdateOptions());

BaseDocument doc = collection.getDocument(info.getKey());
assertThat(doc.getAttribute("hello"), is("world2"));

ArangoCollection.updateDocuments

ArangoCollection.updateDocuments(Collection<T> values, DocumentUpdateOptions options) : MultiDocumentEntity<DocumentUpdateEntity<T>>

Updates multiple documents in the specified collection with the ones in the values, the replaced documents are specified by the _key attributes in the documents in values.

Arguments

values: Collection<T>

A List of documents (POJO, VPackSlice or String for Json)

options: DocumentUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument doc1 = new BaseDocument();
BaseDocument doc2 = new BaseDocument();
BaseDocument doc3 = new BaseDocument();
collection.insertDocuments(Arrays.asList(doc1, doc2, doc3));

// change values of doc1, doc2, doc3

collection.updateDocuments(Arrays.asList(doc1, doc2, doc3), new DocumentUpdateOptions());

ArangoCollection.deleteDocument

ArangoCollection.deleteDocument(String key) : DocumentDeleteEntity<Void>

Deletes the document with the given key from the collection.

Arguments:

key: String

The key of the document

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument document = new BaseDocument("some-key");
collection.insertDocument(document);

collection.deleteDocument("some-key");
// document 'some-collection/some-key' no longer exists

Boolean exists = collection.documentExists("some-key");
assertThat(exists, is(false));

ArangoCollection.deleteDocuments

ArangoCollection.deleteDocuments(Collection<?> values) : MultiDocumentEntity<DocumentDeleteEntity<Void>>

Deletes multiple documents from the collection.

Arguments:

values: Collection<?>

The keys of the documents or the documents themselves

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

collection.deleteDocuments(Arrays.asList("some-key", "some-other-key");
// documents 'some-collection/some-key' and 'some-collection/some-other-key' no longer exists

Indexes

Manipulating indexes

These functions implement the HTTP API for manipulating indexes.

ArangoCollection.ensureHashIndex

ArangoCollection.ensureHashIndex(Iterable<String> fields, HashIndexOptions options) : IndexEntity

Creates a hash index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: HashIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

deduplicate: Boolean

If false, the deduplication of array values is turned off.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.ensureHashIndex(Arrays.asList("a", "b.c"));
// the index has been created with the handle `index.getId()`

ArangoCollection.ensureSkipListIndex

ArangoCollection.ensureSkipListIndex(Iterable<String> fields, SkipListIndexOptions options) : IndexEntity

Creates a skip-list index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: SkipListIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

deduplicate: Boolean

If false, the deduplication of array values is turned off.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.ensureSkipListIndex(Arrays.asList("a", "b.c"));
// the index has been created with the handle `index.getId()`

ArangoCollection.ensureGeoIndex

ArangoCollection.ensureGeoIndex(Iterable<String> fields, GeoIndexOptions options) : IndexEntity

Creates a geo index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: GeoIndexOptions

geoJson: Boolean

If a geo-spatial index on a location is constructed and geoJson is true, then the order within the array is longitude followed by latitude. This corresponds to the format described in.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.ensureGeoIndex(Arrays.asList("latitude", "longitude"));
// the index has been created with the handle `index.getId()`

ArangoCollection.ensureFulltextIndex

ArangoCollection.ensureFulltextIndex(Iterable<String> fields, FulltextIndexOptions options) : IndexEntity

Creates a fulltext index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: FulltextIndexOptions

minLength: Integer

Minimum character length of words to index. Will default to a server-defined value if unspecified. It is thus recommended to set this value explicitly when creating the index.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.ensureFulltextIndex(Arrays.asList("description"));
// the index has been created with the handle `index.getId()`

ArangoCollection.ensurePersistentIndex

ArangoCollection.ensurePersistentIndex(Iterable<String> fields, PersistentIndexOptions options) : IndexEntity

Creates a persistent index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: PersistentIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.ensurePersistentIndex(Arrays.asList("a", "b.c"));
// the index has been created with the handle `index.getId()`

ArangoCollection.getIndex

ArangoCollection.getIndex(String id) : IndexEntity

Fetches information about the index with the given id and returns it.

Arguments

id: String

The index-handle

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

IndexEntity index = collection.getIndex("some-index");

ArangoCollection.getIndexes

ArangoCollection.getIndexes() : Collection<IndexEntity>

Fetches a list of all indexes on this collection.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

Collection<IndexEntity> indexes = collection.getIndexs();

ArangoCollection.deleteIndex

ArangoCollection.deleteIndex(String id) : String

Deletes the index with the given id from the collection.

Arguments

id: String

The index-handle

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

collection.deleteIndex("some-index");

Bulk Import

Bulk importing documents

This function implements the HTTP API for bulk imports.

ArangoCollection.importDocuments

ArangoCollection.importDocuments(Collection<?> values, DocumentImportOptions options) : DocumentImportEntity

ArangoCollection.importDocuments(String values, DocumentImportOptions options) : DocumentImportEntity

Bulk imports the given values into the collection.

Arguments

values: Collection<?> or String

Collection<?>: A list of Objects that will be stored as documents

String: JSON-encoded array of objects that will be stored as documents

options: DocumentImportOptions

fromPrefix: String

An optional prefix for the values in _from attributes. If specified, the value is automatically prepended to each _from input value. This allows specifying just the keys for _from.

toPrefix: String

An optional prefix for the values in _to attributes. If specified, the value is automatically prepended to each _to input value. This allows specifying just the keys for _to.

overwrite: Boolean

If this parameter has a value of true, then all data in the collection will be removed prior to the import. Note that any existing index definitions will be preseved.

waitForSync: Boolean

Wait until documents have been synced to disk before returning.

onDuplicate: OnDuplicate

Controls what action is carried out in case of a unique key constraint violation. Possible values are:

error: this will not import the current document because of the unique key constraint violation. This is the default setting.

update: this will update an existing document in the database with the data specified in the request. Attributes of the existing document that are not present in the request will be preseved.

replace: this will replace an existing document in the database with the data specified in the request.

ignore: this will not update an existing document and simply ignore the error caused by the unique key constraint violation. Note that update, replace and ignore will only work when the import document in the request contains the _key attribute. update and replace may also fail because of secondary unique key constraint violations.

complete: Boolean

If set to true, it will make the whole import fail if any error occurs. Otherwise the import will continue even if some documents cannot be imported.

details: Boolean

If set to true, the result will include an attribute details with details about documents that could not be imported.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoCollection collection = db.collection("some-collection");

BaseDocument doc1 = new BaseDocument();
BaseDocument doc2 = new BaseDocument();
BaseDocument doc3 = new BaseDocument();
collection.importDocuments(Arrays.asList(doc1, doc2, doc3), new DocumentImportOptions());

View

View API

These functions implement the HTTP API for views.

Getting information about the view

See the HTTP API documentation for details.

ArangoView.exists

ArangoView.exists() : boolean

Checks whether the view exists

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoView view = db.view("potatoes");

boolean exists = view.exists();

ArangoView.getInfo

ArangoView.getInfo() : ViewEntity

Returns information about the view.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoView view = db.view("potatoes");

ViewEntity info = view.getInfo();

View Manipulation

Manipulating the view

These functions implement the HTTP API for modifying views.

ArangoDatabase.createView

ArangoDatabase.createView(String name, ViewType type) : ViewEntity

Creates a view of the given type, then returns view information from the server.

Arguments

name: String

The name of the view

type: ViewType

The type of the view

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.createView("myView", ViewType.ARANGO_SEARCH);
// the view "potatoes" now exists

ArangoView.rename

ArangoView.rename(String newName) : ViewEntity

Renames the view.

Arguments

newName: String

The new name

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoView view = db.view("some-view");

ViewEntity result = view.rename("new-view-name")
assertThat(result.getName(), is("new-view-name");
// result contains additional information about the view

ArangoView.drop

ArangoView.drop() : void

Deletes the view from the database.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoView view = db.view("some-view");

view.drop();
// the view "some-view" no longer exists

ArangoSearch Views

ArangoSearch API

These functions implement the HTTP API for ArangoSearch Views.

ArangoDatabase.createArangoSearch

ArangoDatabase.createArangoSearch(String name, ArangoSearchCreateOptions options) : ViewEntity

Creates a ArangoSearch View with the given options, then returns view information from the server.

Arguments

name: String

The name of the view

options: ArangoSearchCreateOptions

locale: String

The default locale used for queries on analyzed string values (default: C).

commitIntervalMsec: Long

Wait at least this many milliseconds between committing index data changes and making them visible to queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, until commit, will cause the index not to account for them and memory usage would continue to grow. For the case where there are a few inserts/updates, a higher value will impact performance and waste disk space for each commit call without any added benefits.

cleanupIntervalStep: Long

Wait at least this many commits between removing unused files in data directory (default: 10, to disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact performance without any added benefits.

threshold: ConsolidateThreshold[]

A list of consolidate thresholds

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
db.createArangoSearch("potatoes", new ArangoSearchPropertiesOptions());
// the ArangoSearch View "potatoes" now exists

ArangoSearch.create

ArangoSearch.create(ArangoSearchCreateOptions options) : ViewEntity

Creates a ArangoSearch View with the given options, then returns view information from the server.

Alternative for ArangoDatabase.createArangoSearch.

Arguments

options: ArangoSearchCreateOptions

locale: String

The default locale used for queries on analyzed string values (default: C).

commitIntervalMsec: Long

Wait at least this many milliseconds between committing index data changes and making them visible to queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, until commit, will cause the index not to account for them and memory usage would continue to grow. For the case where there are a few inserts/updates, a higher value will impact performance and waste disk space for each commit call without any added benefits.

cleanupIntervalStep: Long

Wait at least this many commits between removing unused files in data directory (default: 10, to disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact performance without any added benefits.

threshold: ConsolidateThreshold[]

A list of consolidate thresholds

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoSearch view = db.arangoSearch("potatoes");

view.create(new ArangoSearchPropertiesOptions());
// the ArangoSearch View "potatoes" now exists

ArangoSearch.getProperties

ArangoSearch.getProperties() : ArangoSearchPropertiesEntity

Reads the properties of the specified view.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoSearch view = db.arangoSearch("potatoes");

ArangoSearchPropertiesEntity properties = view.getProperties();

ArangoSearch.updateProperties

ArangoSearch.updateProperties(ArangoSearchPropertiesOptions options) : ArangoSearchPropertiesEntity

Partially changes properties of the view.

Arguments

options: ArangoSearchPropertiesOptions

locale: String

The default locale used for queries on analyzed string values (default: C).

commitIntervalMsec: Long

Wait at least this many milliseconds between committing index data changes and making them visible to queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, until commit, will cause the index not to account for them and memory usage would continue to grow. For the case where there are a few inserts/updates, a higher value will impact performance and waste disk space for each commit call without any added benefits.

cleanupIntervalStep: Long

Wait at least this many commits between removing unused files in data directory (default: 10, to disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact performance without any added benefits.

threshold: ConsolidateThreshold[]

A list of consolidate thresholds

link: CollectionLink[]

A list of linked collections

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoSearch view = db.arangoSearch("some-view");

view.updateProperties(new ArangoSearchPropertiesOptions().link(CollectionLink.on("myCollection").fields(FieldLink.on("value").analyzers("identity"))));

ArangoSearch.replaceProperties

ArangoSearch.replaceProperties(ArangoSearchPropertiesOptions options) : ArangoSearchPropertiesEntity

Changes properties of the view.

Arguments

options: ArangoSearchPropertiesOptions

locale: String

The default locale used for queries on analyzed string values (default: C).

commitIntervalMsec: Long

Wait at least this many milliseconds between committing index data changes and making them visible to queries (default: 60000, to disable use: 0). For the case where there are a lot of inserts/updates, a lower value, until commit, will cause the index not to account for them and memory usage would continue to grow. For the case where there are a few inserts/updates, a higher value will impact performance and waste disk space for each commit call without any added benefits.

cleanupIntervalStep: Long

Wait at least this many commits between removing unused files in data directory (default: 10, to disable use: 0). For the case where the consolidation policies merge segments often (i.e. a lot of commit+consolidate), a lower value will cause a lot of disk space to be wasted. For the case where the consolidation policies rarely merge segments (i.e. few inserts/deletes), a higher value will impact performance without any added benefits.

threshold: ConsolidateThreshold[]

A list of consolidate thresholds

link: CollectionLink[]

A list of linked collections

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoSearch view = db.arangoSearch("some-view");

view.replaceProperties(new ArangoSearchPropertiesOptions().link(CollectionLink.on("myCollection").fields(FieldLink.on("value").analyzers("identity"))));

Cursor

Cursor API

ArangoCursor instances provide an abstraction over the HTTP API's limitations. Unless a method explicitly exhausts the cursor, the driver will only fetch as many batches from the server as necessary. Like the server-side cursors, ArangoCursor instances are incrementally depleted as they are read from.

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class);
// query result list: [1, 2, 3, 4, 5]
Integer value = cursor.next();
assertThat(value, is(1));
// remaining result list: [2, 3, 4, 5]

ArangoCursor.hasNext

ArangoCursor.hasNext() : boolean

Returns true if the cursor has more elements in its current batch of results or the cursor on the server has more batches.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
boolean hasNext = cursor.hasNext();

ArangoCursor.next

ArangoCursor.next() : T

Returns the next element of the query result. If the current element is the last element of the batch and the cursor on the server provides more batches, the next batch is fetched from the server.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Integer value = cursor.next();
assertThat(value, is(1));

ArangoCursor.first

ArangoCursor.first() : T

Returns the first element or {@code null} if no element exists.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("RETURN 1", Integer.class)
Integer value = cursor.first();
assertThat(value, is(1));

ArangoCursor.foreach

ArangoCursor.foreach(Consumer<? super T> action) : void

Performs the given action for each element of the ArangoIterable

Arguments

action: Consumer<? super T>

A action to perform on the elements

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
cursor.foreach(e -> {
  // remaining results: [1, 2, 3, 4, 5]
});

ArangoCursor.map

ArangoCursor.map(Function<? super T, ? extends R> mapper) : ArangoIterable<R>

Returns a ArangoIterable consisting of the results of applying the given function to the elements of this ArangoIterable.

Arguments

mapper: Function<? super T, ? extends R>

A function to apply to each element

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
cursor.map(e -> e * 10).foreach(e -> {
  // remaining results: [10, 20, 30, 40, 50]
});

ArangoCursor.filter

ArangoCursor.filter(Predicate<? super T> predicate) : ArangoIterable<T>

Arguments

predicate: Predicate<? super T>

A predicate to apply to each element to determine if it should be included

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
cursor.filter(e -> e < 4).foreach(e -> {
  // remaining results: [1, 2, 3]
});

ArangoCursor.anyMatch

ArangoCursor.anyMatch(Predicate<? super T> predicate) : boolean

Returns whether any elements of this ArangoIterable match the provided predicate.

Arguments

predicate: Predicate<? super T>

A predicate to apply to elements of this {@code ArangoIterable}

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
boolean match = cursor.anyMatch(e -> e == 3);
assertThat(match, is(true));

ArangoCursor.allMatch

ArangoCursor.anyMatch(Predicate<? super T> predicate) : boolean

Returns whether all elements of this ArangoIterable match the provided predicate.

Arguments

predicate: Predicate<? super T>

A predicate to apply to elements of this {@code ArangoIterable}

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
boolean match = cursor.allMatch(e -> e <= 5);
assertThat(match, is(true));

ArangoCursor.noneMatch

ArangoCursor.noneMatch(Predicate<? super T> predicate) : boolean

Returns whether no elements of this ArangoIterable match the provided predicate.

Arguments

predicate: Predicate<? super T>

A predicate to apply to elements of this {@code ArangoIterable}

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
boolean match = cursor.noneMatch(e -> e > 5);
assertThat(match, is(true));

ArangoCursor.collectInto

ArangoCursor.collectInto(R target) : R

Arguments

Iterates over all elements of this {@code ArangoIterable} and adds each to the given target.

target: R <R extends Collection<? super T>>

The collection to insert into

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Collection<Integer> list = cursor.collectInto(new ArrayList());
// -- or --
Collection<Integer> set = cursor.collectInto(new HashSet());

ArangoCursor.iterator

ArangoCursor.iterator() : Iterator<T>

Returns an iterator over elements of the query result.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Iterator<Integer> iterator = cursor.iterator();

ArangoCursor.asListRemaining

ArangoCursor.asListRemaining() : List<T>

Returns the remaining results as a List.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Collection<Integer> list = cursor.asListRemaining();

ArangoCursor.getCount

ArangoCursor.getCount() : Integer

Returns the total number of result documents available (only available if the query was executed with the count attribute set)

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", new AqlQueryOptions().count(true), Integer.class)
Integer count = cursor.getCount();
assertThat(count, is(5));

ArangoCursor.count

ArangoCursor.count() : long

Returns the count of elements of this ArangoIterable.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
long count = cursor.filter(e -> e < 4).count();
// remaining results: [1, 2, 3]
asserThat(count, is(3L));

ArangoCursor.getStats

ArangoCursor.getStats() : Stats

Returns extra information about the query result. For data-modification queries, the stats will contain the number of modified documents and the number of documents that could not be modified due to an error (if ignoreErrors query option is specified);

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Stats stats = cursor.getStats();

ArangoCursor.getWarnings

ArangoCursor.getWarnings() : Collection<Warning>

Returns warnings which the query could have been produced.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
Collection<Warning> warnings = cursor.getWarnings();

ArangoCursor.isCached

ArangoCursor.isCached() : boolean

Iindicating whether the query result was served from the query cache or not.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoCursor<Integer> cursor = db.query("FOR x IN 1..5 RETURN x", Integer.class)
boolean cached = cursor.isCached();

Graph

Graph API

These functions implement the HTTP API for manipulating graphs.

ArangoDatabase.createGraph

## ArangoDatabase.createGraph(String name, Collection<EdgeDefinition> edgeDefinitions, GraphCreateOptions options) : GraphEntity

Create a new graph in the graph module. The creation of a graph requires the name of the graph and a definition of its edges.

Arguments

name: String

Name of the graph

edgeDefinitions: Collection<EdgeDefinition>

An array of definitions for the edge

options: GraphCreateOptions

orphanCollections: String...

Additional vertex collections

isSmart: Boolean

Define if the created graph should be smart. This only has effect in Enterprise Edition.

replicationFactor: Integer

(The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication between them is synchronous, that is, every write operation to the "leader" copy will be replicated to all "follower" replicas, before the write operation is reported successful. If a server fails, this is detected automatically and one of the servers holding copies take over, usually without an error being reported.

numberOfShards: Integer

The number of shards that is used for every collection within this graph. Cannot be modified later.

smartGraphAttribute: String

The attribute name that is used to smartly shard the vertices of a graph. Every vertex in this Graph has to have this attribute. Cannot be modified later.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

EdgeDefinition edgeDefinition = new EdgeDefinition()
                                  .collection("edges")
                                  .from("start-vertices")
                                  .to("end-vertices");
GraphEntity graph = db.createGraph("some-graph", Arrays.asList(edgeDefinition), new GraphCreateOptions());
// graph now exists

ArangoGraph.create

## ArangoGraph.create(Collection<EdgeDefinition> edgeDefinitions, GraphCreateOptions options) : GraphEntity

Create a new graph in the graph module. The creation of a graph requires the name of the graph and a definition of its edges.

Alternative for ArangoDatabase.createGraph.

Arguments

edgeDefinitions: Collection<EdgeDefinition>

An array of definitions for the edge

options: GraphCreateOptions

orphanCollections: String...

Additional vertex collections

isSmart: Boolean

Define if the created graph should be smart. This only has effect in Enterprise Edition.

replicationFactor: Integer

(The default is 1): in a cluster, this attribute determines how many copies of each shard are kept on different DBServers. The value 1 means that only one copy (no synchronous replication) is kept. A value of k means that k-1 replicas are kept. Any two copies reside on different DBServers. Replication between them is synchronous, that is, every write operation to the "leader" copy will be replicated to all "follower" replicas, before the write operation is reported successful. If a server fails, this is detected automatically and one of the servers holding copies take over, usually without an error being reported.

numberOfShards: Integer

The number of shards that is used for every collection within this graph. Cannot be modified later.

smartGraphAttribute: String

The attribute name that is used to smartly shard the vertices of a graph. Every vertex in this Graph has to have this attribute. Cannot be modified later.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoGraph graph = db.graph("some-graph");
EdgeDefinition edgeDefinition = new EdgeDefinition()
                                  .collection("edges")
                                  .from("start-vertices")
                                  .to("end-vertices");
graph.create(Arrays.asList(edgeDefinition), new GraphCreateOptions());
// graph now exists

ArangoGraph.exists

ArangoGraph.exists() : boolean

Checks whether the graph exists

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoGraph graph = db.graph("some-graph");
boolean exists = graph.exists();

ArangoGraph.getInfo

ArangoGraph.getInfo() : GraphEntity

Retrieves general information about the graph.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoGraph graph = db.graph("some-graph");
GraphEntity info = graph.getInfo();

ArangoGraph.drop

ArangoGraph.drop() : void

Deletes the graph from the database.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoGraph graph = db.graph("some-graph");
graph.drop();
// the graph "some-graph" no longer exists

Vertex Collection

Manipulating the vertex collection

ArangoGraph.vertexCollection

ArangoGraph.vertexCollection(String name) : ArangoVertexCollection

Returns a ArangoVertexCollection instance for the given vertex collection name.

Arguments

name: String

Name of the vertex collection

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

ArangoVertexCollection collection = graph.vertexCollection("some-vertex-collection");

ArangoGraph.getVertexCollections

ArangoGraph.getVertexCollections() : Collection<String>

Fetches all vertex collections from the graph and returns a list of collection names.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

Collection<String> collections = graph.getVertexCollections();

ArangoGraph.addVertexCollection

ArangoGraph.addVertexCollection(String name) : GraphEntity

Adds a vertex collection to the set of collections of the graph. If the collection does not exist, it will be created.

Arguments

name: String

Name of the vertex collection

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

graph.addVertexCollection("some-other-collection");

Edge Collection

Manipulating the edge collection

ArangoGraph.edgeCollection

ArangoGraph.edgeCollection(String name) : ArangoEdgeColleciton

Returns a ArangoEdgeCollection instance for the given edge collection name.

Arguments

name: String

Name of the edge collection

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

ArangoEdgeCollection collection = graph.edgeCollection("some-edge-collection");

ArangoGraph.getEdgeDefinitions

ArangoGraph.getEdgeDefinitions() : Collection<String>

Fetches all edge collections from the graph and returns a list of collection names.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

Collection<String> collections = graph.getEdgeDefinitions();

ArangoGraph.addEdgeDefinition

ArangoGraph.addEdgeDefinition(EdgeDefinition definition) : GraphEntity

Adds the given edge definition to the graph.

Arguments

definition: EdgeDefinition

The edge definition

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

EdgeDefinition edgeDefinition = new EdgeDefinition()
                                  .collection("edges")
                                  .from("start-vertices")
                                  .to("end-vertices");
graph.addEdgeDefinition(edgeDefinition);
// the edge definition has been added to the graph

ArangoGraph.replaceEdgeDefinition

ArangoGraph.replaceEdgeDefinition(EdgeDefinition definition) : GraphEntity

Change one specific edge definition. This will modify all occurrences of this definition in all graphs known to your database.

Arguments

definition: EdgeDefinition

The edge definition

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

EdgeDefinition edgeDefinition = new EdgeDefinition()
                                  .collection("edges")
                                  .from("start-vertices")
                                  .to("end-vertices");
graph.replaceEdgeDefinition(edgeDefinition);
// the edge definition has been modified

ArangoGraph.removeEdgeDefinition

ArangoGraph.removeEdgeDefinition(String definitionName) : GraphEntity

Remove one edge definition from the graph. This will only remove the edge collection, the vertex collections remain untouched and can still be used in your queries.

Arguments

definitionName: String

The name of the edge collection used in the definition

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");

EdgeDefinition edgeDefinition = new EdgeDefinition()
                                  .collection("edges")
                                  .from("start-vertices")
                                  .to("end-vertices");
graph.addEdgeDefinition(edgeDefinition);
// the edge definition has been added to the graph

graph.removeEdgeDefinition("edges");
// the edge definition has been removed

Vertices Manipulation

Manipulating vertices

ArangoVertexCollection.getVertex

ArangoVertexCollection.getVertex(String key, Class<T> type, DocumentReadOptions options) : T

Retrieves the vertex document with the given key from the collection.

Arguments

key: String

The key of the vertex

type: Class<T>

The type of the vertex-document (POJO class, VPackSlice or String for Json)

options: DocumentReadOptions

ifNoneMatch: String

Document revision must not contain If-None-Match

ifMatch: String

Document revision must contain If-Match

catchException: Boolean

Whether or not catch possible thrown exceptions

ArangoVertexCollection.insertVertex

ArangoVertexCollection.insertVertex(T value, VertexCreateOptions options) : VertexEntity

Creates a new vertex in the collection.

Arguments

value: T

A representation of a single vertex (POJO, VPackSlice or String for Json)

options: VertexCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoVertexCollection collection = graph.vertexCollection("some-vertex-collection");

BaseDocument document = new BaseDocument();
document.addAttribute("some", "data");
collection.insertVertex(document, new VertexCreateOptions());

ArangoVertexCollection.replaceVertex

ArangoVertexCollection.replaceVertex(String key, T value, VertexReplaceOptions options) : VertexUpdateEntity

Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is violated.

Arguments

key: String

The key of the vertex

value: T

A representation of a single vertex (POJO, VPackSlice or String for Json)

options: VertexReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Replace a document based on target revision

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoVertexCollection collection = graph.vertexCollection("some-vertex-collection");

BaseDocument document = new BaseDocument();
collection.replaceVertex("some-key", document, new VertexReplaceOptions());

ArangoVertexCollection.updateVertex

ArangoVertexCollection.updateVertex(String key, T value, VertexUpdateOptions options) : VertexUpdateEntity

Updates the vertex with key with the one in the body, provided there is such a vertex and no precondition is violated.

Arguments

key: String

The key of the vertex

value: T

A representation of a single vertex (POJO, VPackSlice or String for Json)

options: VertexUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Update a document based on target revision

keepNull: Boolean

If the intention is to delete existing attributes with the patch command, the URL query parameter keepNull can be used with a value of false. This will modify the behavior of the patch command to remove any attributes from the existing document that are contained in the patch document with an attribute value of null.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoVertexCollection collection = graph.vertexCollection("some-vertex-collection");

BaseDocument document = new BaseDocument();
collection.updateVertex("some-key", document, new VertexUpdateOptions());

ArangoVertexCollection.deleteVertex

ArangoVertexCollection.deleteVertex(String key, VertexDeleteOptions options) : void

Deletes the vertex with the given key from the collection.

Arguments

key: String

The key of the vertex

options : VertexDeleteOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Remove a document based on target revision

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoVertexCollection collection = graph.vertexCollection("some-vertex-collection");

collection.deleteVertex("some-key", new VertexDeleteOptions());

Edges Manipulation

Manipulating edges

ArangoEdgeCollection.getEdge

ArangoEdgeCollection.getEdge(String key, Class<T> type, DocumentReadOptions options) : T

Retrieves the edge document with the given key from the collection.

Arguments

key: String

The key of the edge

type: Class<T>

The type of the edge-document (POJO class, VPackSlice or String for Json)

options: DocumentReadOptions

ifNoneMatch: String

Document revision must not contain If-None-Match

ifMatch: String

Document revision must contain If-Match

catchException: Boolean

Whether or not catch possible thrown exceptions

ArangoEdgeCollection.insertEdge

ArangoEdgeCollection.insertEdge(T value, EdgeCreateOptions options) : EdgeEntity

Creates a new edge in the collection.

Arguments

value: T

A representation of a single edge (POJO, VPackSlice or String for Json)

options: EdgeCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoEdgeCollection collection = graph.edgeCollection("some-edge-collection");

BaseEdgeDocument document = new BaseEdgeDocument("some-from-key", "some-to-key");
document.addAttribute("some", "data");
collection.insertEdge(document, new EdgeCreateOptions());

ArangoEdgeCollection.replaceEdge

ArangoEdgeCollection.replaceEdge(String key, T value, EdgeReplaceOptions options) : EdgeUpdateEntity

Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is violated.

Arguments

key: String

The key of the edge

value: T

A representation of a single edge (POJO, VPackSlice or String for Json)

options: EdgeReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Replace a document based on target revision

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoEdgeCollection collection = graph.edgeCollection("some-edge-collection");

BaseEdgeDocument document = new BaseEdgeDocument("some-from-key", "some-to-key");
collection.replaceEdge("some-key", document, new EdgeReplaceOptions());

ArangoEdgeCollection.updateEdge

ArangoEdgeCollection.updateEdge(String key, T value, EdgeUpdateOptions options) : EdgeUpdateEntity

Updates the edge with key with the one in the body, provided there is such a edge and no precondition is violated.

Arguments

key: String

The key of the edge

value: T

A representation of a single edge (POJO, VPackSlice or String for Json)

options: EdgeUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Update a document based on target revision

keepNull: Boolean

If the intention is to delete existing attributes with the patch command, the URL query parameter keepNull can be used with a value of false. This will modify the behavior of the patch command to remove any attributes from the existing document that are contained in the patch document with an attribute value of null.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoEdgeCollection collection = graph.edgeCollection("some-edge-collection");

BaseEdgeDocument document = new BaseEdgeDocument("some-from-key", "some-to-key");
collection.updateEdge("some-key", document, new EdgeUpdateOptions());

ArangoEdgeCollection.deleteEdge

ArangoEdgeCollection.deleteEdge(String key, EdgeDeleteOptions options) : void

Deletes the edge with the given key from the collection.

Arguments

key: String

The key of the edge

options : EdgeDeleteOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Remove a document based on target revision

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");
ArangoGraph graph = db.graph("some-graph");
ArangoEdgeCollection collection = graph.edgeCollection("some-edge-collection");

collection.deleteEdge("some-key", new EdgeDeleteOptions());

Route

Route API

ArangoRoute instances provide access for arbitrary HTTP requests. This allows easy access to Foxx services and other HTTP APIs not covered by the driver itself.

ArangoRoute.route

ArangoRoute.route(String... path) : ArangoRoute

Returns a new ArangoRoute instance for the given path (relative to the current route) that can be used to perform arbitrary requests.

Arguments

path: String...

The relative URL of the route

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute users = route.route("users");
// equivalent to db.route("my-foxx-service/users")
// or db.route("my-foxx-service", "users")

ArangoRoute.withHeader

ArangoRoute.withHeader(String key, Object value) : ArangoRoute

Header that should be sent with each request to the route.

Arguments

key: String

Header key

value: Object

Header value (the toString() method will be called for the value}

ArangoRoute.withQueryParam

ArangoRoute.withQueryParam(String key, Object value) : ArangoRoute

Query parameter that should be sent with each request to the route.

Arguments

key: String

Query parameter key

value: Object

Query parameter value (the toString() method will be called for the value}

ArangoRoute.withBody

ArangoRoute.withBody(Object body) : ArangoRoute

The response body. The body will be serialized to VPackSlice.

Arguments

body: Object

The request body

ArangoRoute.delete

ArangoRoute.delete() : Response

Performs a DELETE request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute route = route.delete()
// response.getBody() is the response body of calling
// DELETE _db/_system/my-foxx-service

// -- or --

ArangoRoute route = route.route("users/admin").delete()
// response.getBody() is the response body of calling
// DELETE _db/_system/my-foxx-service/users/admin

// -- or --

ArangoRoute route = route.route("users/admin").withQueryParam("permanent", true).delete()
// response.getBody() is the response body of calling
// DELETE _db/_system/my-foxx-service/users/admin?permanent=true

ArangoRoute.get

ArangoRoute.get() : Response

Performs a GET request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
Response response = route.get();
// response.getBody() is the response body of calling
// GET _db/_system/my-foxx-service

// -- or --

Response response = route.route("users").get();
// response.getBody() is the response body of calling
// GET _db/_system/my-foxx-service/users

// -- or --

Response response = route.route("users").withQueryParam("group", "admin").get();
// response.getBody() is the response body of calling
// GET _db/_system/my-foxx-service/users?group=admin

ArangoRoute.head

ArangoRoute.head() : Response

Performs a HEAD request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute route = route.head();
// response is the response object for
// HEAD _db/_system/my-foxx-service

ArangoRoute.patch

ArangoRoute.patch() : Response

Performs a PATCH request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute route = route.patch();
// response.getBody() is the response body of calling
// PATCH _db/_system/my-foxx-service

// -- or --

ArangoRoute route = route.route("users/admin").patch();
// response.getBody() is the response body of calling
// PATCH _db/_system/my-foxx-service/users

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users/admin").withBody(body).patch();
// response.getBody() is the response body of calling
// PATCH _db/_system/my-foxx-service/users/admin
// with JSON request body {"password": "hunter2"}

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users/admin").withBody(body).withQueryParam("admin", true).patch();
// response.getBody() is the response body of calling
// PATCH _db/_system/my-foxx-service/users/admin?admin=true
// with JSON request body {"password": "hunter2"}

ArangoRoute.post

ArangoRoute.post() : Response

Performs a POST request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute route = route.post()
// response.getBody() is the response body of calling
// POST _db/_system/my-foxx-service

// -- or --

ArangoRoute route = route.route("users").post()
// response.getBody() is the response body of calling
// POST _db/_system/my-foxx-service/users

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users").withBody(body).post();
// response.getBody() is the response body of calling
// POST _db/_system/my-foxx-service/users
// with JSON request body {"username": "admin", "password": "hunter2"}

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users").withBody(body).withQueryParam("admin", true).post();
// response.getBody() is the response body of calling
// POST _db/_system/my-foxx-service/users?admin=true
// with JSON request body {"username": "admin", "password": "hunter2"}

ArangoRoute.put

ArangoRoute.put() : Response

Performs a PUT request to the given URL and returns the server response.

Examples

ArangoDB arango = new ArangoDB.Builder().build();
ArangoDatabase db = arango.db("myDB");

ArangoRoute route = db.route("my-foxx-service");
ArangoRoute route = route.put();
// response.getBody() is the response body of calling
// PUT _db/_system/my-foxx-service

// -- or --

ArangoRoute route = route.route("users/admin").put();
// response.getBody() is the response body of calling
// PUT _db/_system/my-foxx-service/users

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users/admin").withBody(body).put();
// response.getBody() is the response body of calling
// PUT _db/_system/my-foxx-service/users/admin
// with JSON request body {"username": "admin", "password": "hunter2"}

// -- or --

VPackSlice body = arango.util().serialize("{ password: 'hunter2' }");
ArangoRoute route = route.route("users/admin").withBody(body).withQueryParam("admin", true).put();
// response.getBody() is the response body of calling
// PUT _db/_system/my-foxx-service/users/admin?admin=true
// with JSON request body {"username": "admin", "password": "hunter2"}

Serialization

Serialization

VelocyPack serialization

Since version 4.1.11 you can extend the VelocyPack serialization by registering additional VPackModules on ArangoDB.Builder.

Java 8 types

GitHub: https://github.com/arangodb/java-velocypack-module-jdk8

Added support for:

java.time.Instant

java.time.LocalDate

java.time.LocalDateTime

java.time.ZonedDateTime

java.time.OffsetDateTime

java.time.ZoneId

java.util.Optional

java.util.OptionalDouble

java.util.OptionalInt

java.util.OptionalLong

<dependencies>
  <dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>velocypack-module-jdk8</artifactId>
    <version>1.1.0</version>
  </dependency>
</dependencies>

ArangoDB arangoDB = new ArangoDB.Builder().registerModule(new VPackJdk8Module()).build();

Scala types

GitHub: https://github.com/arangodb/java-velocypack-module-scala

Added support for:

scala.Option

scala.collection.immutable.List

scala.collection.immutable.Map

scala.math.BigInt

scala.math.BigDecimal

<dependencies>
  <dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>velocypack-module-scala</artifactId>
    <version>1.0.2</version>
  </dependency>
</dependencies>

val arangoDB: ArangoDB = new ArangoDB.Builder().registerModule(new VPackScalaModule).build

Joda-Time

GitHub: https://github.com/arangodb/java-velocypack-module-joda

Added support for:

org.joda.time.DateTime

org.joda.time.Instant

org.joda.time.LocalDate

org.joda.time.LocalDateTime

<dependencies>
  <dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>velocypack-module-joda</artifactId>
    <version>1.1.1</version>
  </dependency>
</dependencies>

ArangoDB arangoDB = new ArangoDB.Builder().registerModule(new VPackJodaModule()).build();

Use of jackson as an alternative serializer

Since version 4.5.2, the driver supports alternative serializer to de-/serialize documents, edges and query results. One implementation is VelocyJack which is based on Jackson working with jackson-dataformat-velocypack.

Note: Any registered custom serializer/deserializer or module will be ignored.

custom serialization

  ArangoDB arangoDB = new ArangoDB.Builder().registerModule(new VPackModule() {
    @Override
    public <C extends VPackSetupContext<C>> void setup(final C context) {
      context.registerDeserializer(MyObject.class, new VPackDeserializer<MyObject>() {
        @Override
        public MyObject deserialize(VPackSlice parent,VPackSlice vpack,
            VPackDeserializationContext context) throws VPackException {
          MyObject obj = new MyObject();
          obj.setName(vpack.get("name").getAsString());
          return obj;
        }
      });
      context.registerSerializer(MyObject.class, new VPackSerializer<MyObject>() {
        @Override
        public void serialize(VPackBuilder builder,String attribute,MyObject value,
            VPackSerializationContext context) throws VPackException {
          builder.add(attribute, ValueType.OBJECT);
          builder.add("name", value.getName());
          builder.close();
        }
      });
    }
  }).build();

JavaBeans

The driver can serialize/deserialize JavaBeans. They need at least a constructor without parameter.

  public class MyObject {

    private String name;
    private Gender gender;
    private int age;

    public MyObject() {
      super();
    }

  }

internal fields

To use Arango-internal fields (like _id, _key, _rev, _from, _to) in your JavaBeans, use the annotation DocumentField.

  public class MyObject {

    @DocumentField(Type.KEY)
    private String key;

    private String name;
    private Gender gender;
    private int age;

    public MyObject() {
      super();
    }

  }

serialized fieldnames

To use a different serialized name for a field, use the annotation SerializedName.

  public class MyObject {

    @SerializedName("title")
    private String name;

    private Gender gender;
    private int age;

    public MyObject() {
      super();
    }

  }

ignore fields

To ignore fields at serialization/deserialization, use the annotation Expose

  public class MyObject {

    @Expose
    private String name;
    @Expose(serialize = true, deserialize = false)
    private Gender gender;
    private int age;

    public MyObject() {
      super();
    }

  }

custom serializer

  ArangoDB arangoDB = new ArangoDB.Builder().registerModule(new VPackModule() {
    @Override
    public <C extends VPackSetupContext<C>> void setup(final C context) {
      context.registerDeserializer(MyObject.class, new VPackDeserializer<MyObject>() {
        @Override
        public MyObject deserialize(VPackSlice parent,VPackSlice vpack,
            VPackDeserializationContext context) throws VPackException {
          MyObject obj = new MyObject();
          obj.setName(vpack.get("name").getAsString());
          return obj;
        }
      });
      context.registerSerializer(MyObject.class, new VPackSerializer<MyObject>() {
        @Override
        public void serialize(VPackBuilder builder,String attribute,MyObject value,
            VPackSerializationContext context) throws VPackException {
          builder.add(attribute, ValueType.OBJECT);
          builder.add("name", value.getName());
          builder.close();
        }
      });
    }
  }).build();

manually serialization

To de-/serialize from and to VelocyPack before or after a database call, use the ArangoUtil from the method util() in ArangoDB, ArangoDatabase, ArangoCollection, ArangoGraph, ArangoEdgeCollectionor ArangoVertexCollection.

  ArangoDB arangoDB = new ArangoDB.Builder();
  VPackSlice vpack = arangoDB.util().serialize(myObj);

  ArangoDB arangoDB = new ArangoDB.Builder();
  MyObject myObj = arangoDB.util().deserialize(vpack, MyObject.class);

ArangoJS - JavaScript Driver

ArangoDB JavaScript Driver

The official ArangoDB low-level JavaScript client.

Note: if you are looking for the ArangoDB JavaScript API in Foxx (or the arangosh interactive shell) please refer to the documentation about the @arangodb module instead; specifically the db object exported by the @arangodb module. The JavaScript driver is only meant to be used when accessing ArangoDB from outside the database.

Getting Started

Reference

Changelog

Getting Started

ArangoDB JavaScript Driver - Getting Started

Compatibility

ArangoJS is compatible with ArangoDB 3.0 and later. For using ArangoJS with 2.8 or earlier see the upgrade note below. ArangoJS is tested against the two most-recent releases of ArangoDB 3 (currently 3.2 and 3.3) as well as the most recent version of 2.8 and the latest development version.

The yarn/npm distribution of ArangoJS is compatible with Node.js versions 9.x (latest), 8.x (LTS) and 6.x (LTS). Node.js version support follows the official Node.js long-term support schedule.

The included browser build is compatible with Internet Explorer 11 and recent versions of all modern browsers (Edge, Chrome, Firefox and Safari).

Versions outside this range may be compatible but are not actively supported.

Upgrade note: If you want to use arangojs with ArangoDB 2.8 or earlier remember to set the appropriate arangoVersion option (e.g. 20800 for version 2.8.0). The current default value is 30000 (indicating compatibility with version 3.0.0 and newer). The driver will behave differently depending on this value when using APIs that have changed between these versions.

Upgrade note for 6.0.0: All asynchronous functions now return promises and support for node-style callbacks has been removed. If you are using a version of Node.js older than Node.js 6.x LTS ("Boron") make sure you replace the native Promise implementation with a substitute like bluebird to avoid a known memory leak in older versions of the V8 JavaScript engine.

Versions

The version number of this driver does not indicate supported ArangoDB versions!

This driver uses semantic versioning:

A change in the bugfix version (e.g. X.Y.0 -> X.Y.1) indicates internal changes and should always be safe to upgrade.

A change in the minor version (e.g. X.1.Z -> X.2.0) indicates additions and backwards-compatible changes that should not affect your code.

A change in the major version (e.g. 1.Y.Z -> 2.0.0) indicates breaking changes that require changes in your code to upgrade.

If you are getting weird errors or functions seem to be missing, make sure you are using the latest version of the driver and following documentation written for a compatible version. If you are following a tutorial written for an older version of arangojs, you can install that version using the <name>@<version> syntax:

# for version 4.x.x
yarn add arangojs@4
# - or -
npm install --save arangojs@4

You can find the documentation for each version by clicking on the corresponding date on the left in the list of version tags.

Testing

Run the tests using the yarn test or npm test commands:

yarn test
# - or -
npm test

By default the tests will be run against a server listening on http://localhost:8529 (using username root with no password). To override this, you can set the environment variable TEST_ARANGODB_URL to something different:

TEST_ARANGODB_URL=http://myserver.local:8530 yarn test
# - or -
TEST_ARANGODB_URL=http://myserver.local:8530 npm test

Install

With Yarn or NPM

yarn add arangojs
# - or -
npm install --save arangojs

With Bower

Starting with arangojs 6.0.0 Bower is no longer supported and the browser build is now included in the NPM release (see below).

From source

git clone https://github.com/arangodb/arangojs.git
cd arangojs
npm install
npm run dist

For browsers

For production use arangojs can be installed with Yarn or NPM like any other dependency. Just use arangojs like you would in your server code:

import { Database } from "arangojs";
// -- or --
var arangojs = require("arangojs");

Additionally the NPM release comes with a precompiled browser build:

var arangojs = require("arangojs/lib/web");

You can also use unpkg during development:

< !-- note the path includes the version number (e.g. 6.0.0) -- >
<script src="https://unpkg.com/arangojs@6.0.0/lib/web.js"></script>
<script>
var db = new arangojs.Database();
db.listCollections().then(function (collections) {
  alert("Your collections: " + collections.map(function (collection) {
    return collection.name;
  }).join(", "));
});
</script>

If you are targetting browsers older than Internet Explorer 11 you may want to use babel with a polyfill to provide missing functionality needed to use arangojs.

When loading the browser build with a script tag make sure to load the polyfill first:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="https://unpkg.com/arangojs@6.0.0/lib/web.js"></script>

Basic usage example

// Modern JavaScript
import { Database, aql } from "arangojs";
const db = new Database();
(async function() {
  const now = Date.now();
  try {
    const cursor = await db.query(aql`
      RETURN ${now}
    `);
    const result = await cursor.next();
    // ...
  } catch (err) {
    // ...
  }
})();

// or plain old Node-style
var arangojs = require("arangojs");
var db = new arangojs.Database();
var now = Date.now();
db
  .query({
    query: "RETURN @value",
    bindVars: { value: now }
  })
  .then(function(cursor) {
    return cursor.next().then(function(result) {
      // ...
    });
  })
  .catch(function(err) {
    // ...
  });

// Using different databases
const db = new Database({
  url: "http://localhost:8529"
});
db.useDatabase("pancakes");
db.useBasicAuth("root", "");
// The database can be swapped at any time
db.useDatabase("waffles");
db.useBasicAuth("admin", "maplesyrup");

// Using ArangoDB behind a reverse proxy
const db = new Database({
  url: "http://myproxy.local:8000",
  isAbsolute: true // don't automatically append database path to URL
});

// Trigger ArangoDB 2.8 compatibility mode
const db = new Database({
  arangoVersion: 20800
});

For AQL please check out the aql template tag for writing parametrized AQL queries without making your code vulnerable to injection attacks.

Error responses

If arangojs encounters an API error, it will throw an ArangoError with an errorNum as defined in the ArangoDB documentation as well as a code and statusCode property indicating the intended and actual HTTP status code of the response.

For any other error responses (4xx/5xx status code), it will throw an HttpError error with the status code indicated by the code and statusCode properties.

If the server response did not indicate an error but the response body could not be parsed, a SyntaxError may be thrown instead.

In all of these cases the error object will additionally have a response property containing the server response object.

If the request failed at a network level or the connection was closed without receiving a response, the underlying error will be thrown instead.

Examples

// Using async/await
try {
  const info = await db.createDatabase('mydb');
  // database created
} catch (err) {
  console.error(err.stack);
}

// Using promises with arrow functions
db.createDatabase('mydb')
.then(
  info => {
    // database created
  },
  err => console.error(err.stack)
);

Note: the examples in the remainder of this documentation use async/await and other modern language features like multi-line strings and template tags. When developing for an environment without support for these language features, just use promises instead as in the above example.

Reference

ArangoDB JavaScript Driver - Reference

Database

Database Manipulation

Collection Access

View Access

Queries

AQL User Functions

Transactions

Graph Access

Foxx Services

HTTP Routes

Collection

Collection Manipulation

Document Manipulation

DocumentCollection

EdgeCollection

Indexes

Simple Queries

Bulk Import

View Manipulation

Cursor

Graph

Vertices

Edges

VertexCollection

EdgeCollection

Route

Database

Database API

new Database

new Database([config]): Database

Creates a new Database instance.

If config is a string, it will be interpreted as config.url.

Arguments

config: Object (optional)

An object with the following properties:

url: string | Array<string> (Default: http://localhost:8529)

Base URL of the ArangoDB server or list of server URLs.

When working with a cluster or a single server with leader/follower failover, the method db.acquireHostList can be used to automatically pick up additional coordinators/followers at any point.

Note: As of arangojs 6.0.0 it is no longer possible to pass the username or password from the URL.

If you want to use ArangoDB with authentication, see useBasicAuth or useBearerAuth methods.

If you need to support self-signed HTTPS certificates, you may have to add your certificates to the agentOptions, e.g.:

agentOptions: {
  ca: [
    fs.readFileSync(".ssl/sub.class1.server.ca.pem"),
    fs.readFileSync(".ssl/ca.pem")
  ];
}

isAbsolute: boolean (Default: false)

If this option is explicitly set to true, the url will be treated as the absolute database path. This is an escape hatch to allow using arangojs with database APIs exposed with a reverse proxy and makes it impossible to switch databases with useDatabase or using acquireHostList.

arangoVersion: number (Default: 30000)

Value of the x-arango-version header. This should match the lowest version of ArangoDB you expect to be using. The format is defined as XYYZZ where X is the major version, Y is the two-digit minor version and Z is the two-digit bugfix version.

Example: 30102 corresponds to version 3.1.2 of ArangoDB.

Note: The driver will behave differently when using different major versions of ArangoDB to compensate for API changes. Some functions are not available on every major version of ArangoDB as indicated in their descriptions below (e.g. collection.first, collection.bulkUpdate).

headers: Object (optional)

An object with additional headers to send with every request.

Header names should always be lowercase. If an "authorization" header is provided, it will be overridden when using useBasicAuth or useBearerAuth.

agent: Agent (optional)

An http Agent instance to use for connections.

By default a new http.Agent (or https.Agent) instance will be created using the agentOptions.

This option has no effect when using the browser version of arangojs.

agentOptions: Object (Default: see below)

An object with options for the agent. This will be ignored if agent is also provided.

Default: {maxSockets: 3, keepAlive: true, keepAliveMsecs: 1000}. Browser default: {maxSockets: 3, keepAlive: false};

The option maxSockets can also be used to limit how many requests arangojs will perform concurrently. The maximum number of requests is equal to maxSockets * 2 with keepAlive: true or equal to maxSockets with keepAlive: false.

In the browser version of arangojs this option can be used to pass additional options to the underlying calls of the xhr module.

loadBalancingStrategy: string (Default: "NONE")

Determines the behavior when multiple URLs are provided:

NONE: No load balancing. All requests will be handled by the first URL in the list until a network error is encountered. On network error, arangojs will advance to using the next URL in the list.

ONE_RANDOM: Randomly picks one URL from the list initially, then behaves like NONE.

ROUND_ROBIN: Every sequential request uses the next URL in the list.

maxRetries: number or false (Default: 0)

Determines the behavior when a request fails because the underlying connection to the server could not be opened (i.e. ECONNREFUSED in Node.js):

false: the request fails immediately.

0: the request is retried until a server can be reached but only a total number of times matching the number of known servers (including the initial failed request).

any other number: the request is retried until a server can be reached the request has been retried a total of maxRetries number of times (not including the initial failed request).

When working with a single server without leader/follower failover, the retries (if any) will be made to the same server.

This setting currently has no effect when using arangojs in a browser.

Note: Requests bound to a specific server (e.g. fetching query results) will never be retried automatically and ignore this setting.

database.close

database.close(): void

Closes all active connections of the database instance. Can be used to clean up idling connections during longer periods of inactivity.

Note: This method currently has no effect in the browser version of arangojs.

Examples

const db = new Database();
const sessions = db.collection("sessions");
// Clean up expired sessions once per hour
setInterval(async () => {
  await db.query(aql`
    FOR session IN ${sessions}
    FILTER session.expires < DATE_NOW()
    REMOVE session IN ${sessions}
  `);
  // Make sure to close the connections because they're no longer used
  db.close();
}, 1000 * 60 * 60);

Database Manipulation

Manipulating databases

These functions implement the HTTP API for manipulating databases.

database.acquireHostList

async database.acquireHostList(): this

Updates the URL list by requesting a list of all coordinators in the cluster and adding any endpoints not initially specified in the url configuration.

For long-running processes communicating with an ArangoDB cluster it is recommended to run this method repeatedly (e.g. once per hour) to make sure new coordinators are picked up correctly and can be used for fail-over or load balancing.

Note: This method can not be used when the arangojs instance was created with isAbsolute: true.

database.useDatabase

database.useDatabase(databaseName): this

Updates the Database instance and its connection string to use the given databaseName, then returns itself.

Note: This method can not be used when the arangojs instance was created with isAbsolute: true.

Arguments

databaseName: string

The name of the database to use.

Examples

const db = new Database();
db.useDatabase("test");
// The database instance now uses the database "test".

database.useBasicAuth

database.useBasicAuth([username, [password]]): this

Updates the Database instance's authorization header to use Basic authentication with the given username and password, then returns itself.

Arguments

username: string (Default: "root")

The username to authenticate with.

password: string (Default: "")

The password to authenticate with.

Examples

const db = new Database();
db.useDatabase("test");
db.useBasicAuth("admin", "hunter2");
// The database instance now uses the database "test"
// with the username "admin" and password "hunter2".

database.useBearerAuth

database.useBearerAuth(token): this

Updates the Database instance's authorization header to use Bearer authentication with the given authentication token, then returns itself.

Arguments

token: string

The token to authenticate with.

Examples

const db = new Database();
db.useBearerAuth("keyboardcat");
// The database instance now uses Bearer authentication.

database.login

async database.login([username, [password]]): string

Validates the given database credentials and exchanges them for an authentication token, then uses the authentication token for future requests and returns it.

Arguments

username: string (Default: "root")

The username to authenticate with.

password: string (Default: "")

The password to authenticate with.

Examples

const db = new Database();
db.useDatabase("test");
await db.login("admin", "hunter2");
// The database instance now uses the database "test"
// with an authentication token for the "admin" user.

database.version

async database.version(): Object

Fetches the ArangoDB version information for the active database from the server.

Examples

const db = new Database();
const version = await db.version();
// the version object contains the ArangoDB version information.

database.createDatabase

async database.createDatabase(databaseName, [users]): Object

Creates a new database with the given databaseName.

Arguments

databaseName: string

Name of the database to create.

users: Array<Object> (optional)

If specified, the array must contain objects with the following properties:

username: string

The username of the user to create for the database.

passwd: string (Default: empty)

The password of the user.

active: boolean (Default: true)

Whether the user is active.

extra: Object (optional)

An object containing additional user data.

Examples

const db = new Database();
const info = await db.createDatabase('mydb', [{username: 'root'}]);
// the database has been created

database.exists

async database.exists(): boolean

Checks whether the database exists.

Examples

const db = new Database();
const result = await db.exists();
// result indicates whether the database exists

database.get

async database.get(): Object

Fetches the database description for the active database from the server.

Examples

const db = new Database();
const info = await db.get();
// the database exists

database.listDatabases

async database.listDatabases(): Array<string>

Fetches all databases from the server and returns an array of their names.

Examples

const db = new Database();
const names = await db.listDatabases();
// databases is an array of database names

database.listUserDatabases

async database.listUserDatabases(): Array<string>

Fetches all databases accessible to the active user from the server and returns an array of their names.

Examples

const db = new Database();
const names = await db.listUserDatabases();
// databases is an array of database names

database.dropDatabase

async database.dropDatabase(databaseName): Object

Deletes the database with the given databaseName from the server.

const db = new Database();
await db.dropDatabase('mydb');
// database "mydb" no longer exists

database.truncate

async database.truncate([excludeSystem]): Object

Deletes all documents in all collections in the active database.

Arguments

excludeSystem: boolean (Default: true)

Whether system collections should be excluded. Note that this option will be ignored because truncating system collections is not supported anymore for some system collections.

Examples

const db = new Database();

await db.truncate();
// all non-system collections in this database are now empty

Collection Access

Accessing collections

These functions implement the HTTP API for accessing collections.

database.collection

database.collection(collectionName): DocumentCollection

Returns a DocumentCollection instance for the given collection name.

Arguments

collectionName: string

Name of the edge collection.

Examples

const db = new Database();
const collection = db.collection("potatoes");

database.edgeCollection

database.edgeCollection(collectionName): EdgeCollection

Returns an EdgeCollection instance for the given collection name.

Arguments

collectionName: string

Name of the edge collection.

Examples

const db = new Database();
const collection = db.edgeCollection("potatoes");

database.listCollections

async database.listCollections([excludeSystem]): Array<Object>

Fetches all collections from the database and returns an array of collection descriptions.

Arguments

excludeSystem: boolean (Default: true)

Whether system collections should be excluded.

Examples

const db = new Database();

const collections = await db.listCollections();
// collections is an array of collection descriptions
// not including system collections

// -- or --

const collections = await db.listCollections(false);
// collections is an array of collection descriptions
// including system collections

database.collections

async database.collections([excludeSystem]): Array<Collection>

Fetches all collections from the database and returns an array of DocumentCollection and EdgeCollection instances for the collections.

Arguments

excludeSystem: boolean (Default: true)

Whether system collections should be excluded.

Examples

const db = new Database();

const collections = await db.collections()
// collections is an array of DocumentCollection
// and EdgeCollection instances
// not including system collections

// -- or --

const collections = await db.collections(false)
// collections is an array of DocumentCollection
// and EdgeCollection instances
// including system collections

View Access

Accessing views

These functions implement the HTTP API for accessing views.

database.arangoSearchView

database.arangoSearchView(viewName): ArangoSearchView

Returns a ArangoSearchView instance for the given view name.

Arguments

viewName: string

Name of the arangosearch view.

Examples

const db = new Database();
const view = db.arangoSearchView("potatoes");

database.listViews

async database.listViews(): Array<Object>

Fetches all views from the database and returns an array of view descriptions.

Examples

const db = new Database();

const views = await db.listViews();
// views is an array of view descriptions

database.views

async database.views([excludeSystem]): Array<View>

Fetches all views from the database and returns an array of ArangoSearchView instances for the views.

Examples

const db = new Database();

const views = await db.views()
// views is an array of ArangoSearchView instances

Queries

Queries

This function implements the HTTP API for single roundtrip AQL queries.

For collection-specific queries see simple queries.

database.query

async database.query(query, [bindVars,] [opts]): Cursor

Performs a database query using the given query and bindVars, then returns a new Cursor instance for the result list.

Arguments

query: string

An AQL query string or a query builder instance.

bindVars: Object (optional)

An object defining the variables to bind the query to.

opts: Object (optional)

Additional parameter object that will be passed to the query API. Possible keys are count and options (explained below)

If opts.count is set to true, the cursor will have a count property set to the query result count. Possible key options in opts.options include: failOnWarning, cache, profile or skipInaccessibleCollections. For a complete list of query settings please reference the arangodb.com documentation.

If query is an object with query and bindVars properties, those will be used as the values of the respective arguments instead.

Examples

const db = new Database();
const active = true;

// Using the aql template tag
const cursor = await db.query(aql`
  FOR u IN _users
  FILTER u.authData.active == ${active}
  RETURN u.user
`);
// cursor is a cursor for the query result

// -- or --

// Old-school JS with explicit bindVars:
db.query(
  'FOR u IN _users ' +
  'FILTER u.authData.active == @active ' +
  'RETURN u.user',
  {active: true}
).then(function (cursor) {
  // cursor is a cursor for the query result
});

aql

aql(strings, ...args): Object

Template string handler (aka template tag) for AQL queries. Converts a template string to an object that can be passed to database.query by converting arguments to bind variables.

Note: If you want to pass a collection name as a bind variable, you need to pass a Collection instance (e.g. what you get by passing the collection name to db.collection) instead. If you see the error "array expected as operand to FOR loop", you're likely passing a collection name instead of a collection instance.

Examples

const userCollection = db.collection("_users");
const role = "admin";

const query = aql`
  FOR user IN ${userCollection}
  FILTER user.role == ${role}
  RETURN user
`;

// -- is equivalent to --
const query = {
  query: "FOR user IN @@value0 FILTER user.role == @value1 RETURN user",
  bindVars: { "@value0": userCollection.name, value1: role }
};

Note how the aql template tag automatically handles collection references (@@value0 instead of @value0) for us so you don't have to worry about counting at-symbols.

Because the aql template tag creates actual bindVars instead of inlining values directly, it also avoids injection attacks via malicious parameters:

// malicious user input
const email = '" || (FOR x IN secrets REMOVE x IN secrets) || "';

// DON'T do this!
const query = `
  FOR user IN users
  FILTER user.email == "${email}"
  RETURN user
`;
// FILTER user.email == "" || (FOR x IN secrets REMOVE x IN secrets) || ""

// instead do this!
const query = aql`
  FOR user IN users
  FILTER user.email == ${email}
  RETURN user
`;
// FILTER user.email == @value0

AQL User Functions

Managing AQL user functions

These functions implement the HTTP API for managing AQL user functions.

database.listFunctions

async database.listFunctions(): Array<Object>

Fetches a list of all AQL user functions registered with the database.

Examples

const db = new Database();
const functions = db.listFunctions();
// functions is a list of function descriptions

database.createFunction

async database.createFunction(name, code): Object

Creates an AQL user function with the given name and code if it does not already exist or replaces it if a function with the same name already existed.

Arguments

name: string

A valid AQL function name, e.g.: "myfuncs::accounting::calculate_vat".

code: string

A string evaluating to a JavaScript function (not a JavaScript function object).

Examples

const db = new Database();
await db.createFunction(
  'ACME::ACCOUNTING::CALCULATE_VAT',
  String(function (price) {
    return price * 0.19;
  })
);
// Use the new function in an AQL query with template handler:
const cursor = await db.query(aql`
  FOR product IN products
  RETURN MERGE(
    {vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price)},
    product
  )
`);
// cursor is a cursor for the query result

database.dropFunction

async database.dropFunction(name, [group]): Object

Deletes the AQL user function with the given name from the database.

Arguments

name: string

The name of the user function to drop.

group: boolean (Default: false)

If set to true, all functions with a name starting with name will be deleted; otherwise only the function with the exact name will be deleted.

Examples

const db = new Database();
await db.dropFunction('ACME::ACCOUNTING::CALCULATE_VAT');
// the function no longer exists

Transactions

Transactions

This function implements the HTTP API for transactions.

database.transaction

async database.transaction(collections, action, [params, [options]]): Object

Performs a server-side transaction and returns its return value.

Arguments

collections: Object

An object with the following properties:

read: Array<string> (optional)

An array of names (or a single name) of collections that will be read from during the transaction.

write: Array<string> (optional)

An array of names (or a single name) of collections that will be written to or read from during the transaction.

action: string

A string evaluating to a JavaScript function to be executed on the server.

Note: For accessing the database from within ArangoDB, see the documentation for the @arangodb module in ArangoDB.

params: Object (optional)

Available as variable params when the action function is being executed on server. Check the example below.

options: Object (optional)

An object with any of the following properties:

lockTimeout: number (optional)

Determines how long the database will wait while attempting to gain locks on collections used by the transaction before timing out.

waitForSync: boolean (optional)

Determines whether to force the transaction to write all data to disk before returning.

maxTransactionSize: number (optional)

Determines the transaction size limit in bytes. Honored by the RocksDB storage engine only.

intermediateCommitCount: number (optional)

Determines the maximum number of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

intermediateCommitSize: number (optional)

Determine the maximum total size of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

If collections is an array or string, it will be treated as collections.write.

Please note that while action should be a string evaluating to a well-formed JavaScript function, it's not possible to pass in a JavaScript function directly because the function needs to be evaluated on the server and will be transmitted in plain text.

For more information on transactions, see the HTTP API documentation for transactions.

Examples

const db = new Database();
const action = String(function (params) {
  // This code will be executed inside ArangoDB!
  const db = require('@arangodb').db;
  return db._query(aql`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
  `).toArray();
});

const result = await db.transaction(
  {read: '_users'},
  action,
  {age: 12}
);
// result contains the return value of the action

Graph Access

Accessing graphs

These functions implement the HTTP API for accessing general graphs.

database.graph

database.graph(graphName): Graph

Returns a Graph instance representing the graph with the given graph name.

database.listGraphs

async database.listGraphs(): Array<Object>

Fetches all graphs from the database and returns an array of graph descriptions.

Examples

const db = new Database();
const graphs = await db.listGraphs();
// graphs is an array of graph descriptions

database.graphs

async database.graphs(): Array<Graph>

Fetches all graphs from the database and returns an array of Graph instances for the graphs.

Examples

const db = new Database();
const graphs = await db.graphs();
// graphs is an array of Graph instances

Foxx Services

Managing Foxx services

database.listServices

async database.listServices([excludeSystem]): Array<Object>

Fetches a list of all installed service.

Arguments

excludeSystem: boolean (Default: true)

Whether system services should be excluded.

Examples

const services = await db.listServices();

// -- or --

const services = await db.listServices(false);

database.installService

async database.installService(mount, source, [options]): Object

Installs a new service.

Arguments

mount: string

The service's mount point, relative to the database.

source: Buffer | Readable | File | string

The service bundle to install.

options: Object (optional)

An object with any of the following properties:

configuration: Object (optional)

An object mapping configuration option names to values.

dependencies: Object (optional)

An object mapping dependency aliases to mount points.

development: boolean (Default: false)

Whether the service should be installed in development mode.

legacy: boolean (Default: false)

Whether the service should be installed in legacy compatibility mode.

This overrides the engines option in the service manifest (if any).

setup: boolean (Default: true)

Whether the setup script should be executed.

Examples

const source = fs.createReadStream('./my-foxx-service.zip');
const info = await db.installService('/hello', source);

// -- or --

const source = fs.readFileSync('./my-foxx-service.zip');
const info = await db.installService('/hello', source);

// -- or --

const element = document.getElementById('my-file-input');
const source = element.files[0];
const info = await db.installService('/hello', source);

database.replaceService

async database.replaceService(mount, source, [options]): Object

Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.

Arguments

mount: string

The service's mount point, relative to the database.

source: Buffer | Readable | File | string

The service bundle to replace the existing service with.

options: Object (optional)

An object with any of the following properties:

configuration: Object (optional)

An object mapping configuration option names to values.

This configuration will replace the existing configuration.

dependencies: Object (optional)

An object mapping dependency aliases to mount points.

These dependencies will replace the existing dependencies.

development: boolean (Default: false)

Whether the new service should be installed in development mode.

legacy: boolean (Default: false)

Whether the new service should be installed in legacy compatibility mode.

This overrides the engines option in the service manifest (if any).

teardown: boolean (Default: true)

Whether the teardown script of the old service should be executed.

setup: boolean (Default: true)

Whether the setup script of the new service should be executed.

Examples

const source = fs.createReadStream('./my-foxx-service.zip');
const info = await db.replaceService('/hello', source);

// -- or --

const source = fs.readFileSync('./my-foxx-service.zip');
const info = await db.replaceService('/hello', source);

// -- or --

const element = document.getElementById('my-file-input');
const source = element.files[0];
const info = await db.replaceService('/hello', source);

database.upgradeService

async database.upgradeService(mount, source, [options]): Object

Replaces an existing service with a new service while retaining the old service's configuration and dependencies.

Arguments

mount: string

The service's mount point, relative to the database.

source: Buffer | Readable | File | string

The service bundle to replace the existing service with.

options: Object (optional)

An object with any of the following properties:

configuration: Object (optional)

An object mapping configuration option names to values.

This configuration will be merged into the existing configuration.

dependencies: Object (optional)

An object mapping dependency aliases to mount points.

These dependencies will be merged into the existing dependencies.

development: boolean (Default: false)

Whether the new service should be installed in development mode.

legacy: boolean (Default: false)

Whether the new service should be installed in legacy compatibility mode.

This overrides the engines option in the service manifest (if any).

teardown: boolean (Default: false)

Whether the teardown script of the old service should be executed.

setup: boolean (Default: true)

Whether the setup script of the new service should be executed.

Examples

const source = fs.createReadStream('./my-foxx-service.zip');
const info = await db.upgradeService('/hello', source);

// -- or --

const source = fs.readFileSync('./my-foxx-service.zip');
const info = await db.upgradeService('/hello', source);

// -- or --

const element = document.getElementById('my-file-input');
const source = element.files[0];
const info = await db.upgradeService('/hello', source);

database.uninstallService

async database.uninstallService(mount, [options]): void

Completely removes a service from the database.

Arguments

mount: string

The service's mount point, relative to the database.

options: Object (optional)

An object with any of the following properties:

teardown: boolean (Default: true)

Whether the teardown script should be executed.

Examples

await db.uninstallService('/my-service');
// service was uninstalled

database.getService

async database.getService(mount): Object

Retrieves information about a mounted service.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const info = await db.getService('/my-service');
// info contains detailed information about the service

database.getServiceConfiguration

async database.getServiceConfiguration(mount, [minimal]): Object

Retrieves an object with information about the service's configuration options and their current values.

Arguments

mount: string

The service's mount point, relative to the database.

minimal: boolean (Default: false)

Only return the current values.

Examples

const config = await db.getServiceConfiguration('/my-service');
// config contains information about the service's configuration

database.replaceServiceConfiguration

async database.replaceServiceConfiguration(mount, configuration, [minimal]): Object

Replaces the configuration of the given service.

Arguments

mount: string

The service's mount point, relative to the database.

configuration: Object

An object mapping configuration option names to values.

minimal: boolean (Default: false)

Only return the current values and warnings (if any).

Note: when using ArangoDB 3.2.8 or older, enabling this option avoids triggering a second request to the database.

Examples

const config = {currency: 'USD', locale: 'en-US'};
const info = await db.replaceServiceConfiguration('/my-service', config);
// info.values contains information about the service's configuration
// info.warnings contains any validation errors for the configuration

database.updateServiceConfiguration

async database.updateServiceConfiguration(mount, configuration, [minimal]): Object

Updates the configuration of the given service my merging the new values into the existing ones.

Arguments

mount: string

The service's mount point, relative to the database.

configuration: Object

An object mapping configuration option names to values.

minimal: boolean (Default: false)

Only return the current values and warnings (if any).

Note: when using ArangoDB 3.2.8 or older, enabling this option avoids triggering a second request to the database.

Examples

const config = {locale: 'en-US'};
const info = await db.updateServiceConfiguration('/my-service', config);
// info.values contains information about the service's configuration
// info.warnings contains any validation errors for the configuration

database.getServiceDependencies

async database.getServiceDependencies(mount, [minimal]): Object

Retrieves an object with information about the service's dependencies and their current mount points.

Arguments

mount: string

The service's mount point, relative to the database.

minimal: boolean (Default: false)

Only return the current values and warnings (if any).

Examples

const deps = await db.getServiceDependencies('/my-service');
// deps contains information about the service's dependencies

database.replaceServiceDependencies

async database.replaceServiceDependencies(mount, dependencies, [minimal]): Object

Replaces the dependencies for the given service.

Arguments

mount: string

The service's mount point, relative to the database.

dependencies: Object

An object mapping dependency aliases to mount points.

minimal: boolean (Default: false)

Only return the current values and warnings (if any).

Note: when using ArangoDB 3.2.8 or older, enabling this option avoids triggering a second request to the database.

Examples

const deps = {mailer: '/mailer-api', auth: '/remote-auth'};
const info = await db.replaceServiceDependencies('/my-service', deps);
// info.values contains information about the service's dependencies
// info.warnings contains any validation errors for the dependencies

database.updateServiceDependencies

async database.updateServiceDependencies(mount, dependencies, [minimal]): Object

Updates the dependencies for the given service by merging the new values into the existing ones.

Arguments

mount: string

The service's mount point, relative to the database.

dependencies: Object

An object mapping dependency aliases to mount points.

minimal: boolean (Default: false)

Only return the current values and warnings (if any).

Note: when using ArangoDB 3.2.8 or older, enabling this option avoids triggering a second request to the database.

Examples

const deps = {mailer: '/mailer-api'};
const info = await db.updateServiceDependencies('/my-service', deps);
// info.values contains information about the service's dependencies
// info.warnings contains any validation errors for the dependencies

database.enableServiceDevelopmentMode

async database.enableServiceDevelopmentMode(mount): Object

Enables development mode for the given service.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const info = await db.enableServiceDevelopmentMode('/my-service');
// the service is now in development mode
// info contains detailed information about the service

database.disableServiceDevelopmentMode

async database.disableServiceDevelopmentMode(mount): Object

Disabled development mode for the given service and commits the service state to the database.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const info = await db.disableServiceDevelopmentMode('/my-service');
// the service is now in production mode
// info contains detailed information about the service

database.listServiceScripts

async database.listServiceScripts(mount): Object

Retrieves a list of the service's scripts.

Returns an object mapping each name to a more readable representation.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const scripts = await db.listServiceScripts('/my-service');
// scripts is an object listing the service scripts

database.runServiceScript

async database.runServiceScript(mount, name, [scriptArg]): any

Runs a service script and returns the result.

Arguments

mount: string

The service's mount point, relative to the database.

name: string

Name of the script to execute.

scriptArg: any

Value that will be passed as an argument to the script.

Examples

const result = await db.runServiceScript('/my-service', 'setup');
// result contains the script's exports (if any)

database.runServiceTests

async database.runServiceTests(mount, [reporter]): any

Runs the tests of a given service and returns a formatted report.

Arguments

mount: string

The service's mount point, relative to the database

options: Object (optional)

An object with any of the following properties:

reporter: string (Default: default)

The reporter to use to process the test results.

As of ArangoDB 3.2 the following reporters are supported:

stream: an array of event objects

suite: nested suite objects with test results

xunit: JSONML representation of an XUnit report

tap: an array of TAP event strings

default: an array of test results

idiomatic: boolean (Default: false)

Whether the results should be converted to the apropriate string representation:

xunit reports will be formatted as XML documents

tap reports will be formatted as TAP streams

stream reports will be formatted as JSON-LD streams

Examples

const opts = {reporter: 'xunit', idiomatic: true};
const result = await db.runServiceTests('/my-service', opts);
// result contains the XUnit report as a string

database.downloadService

async database.downloadService(mount): Buffer | Blob

Retrieves a zip bundle containing the service files.

Returns a Buffer in Node or Blob in the browser version.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const bundle = await db.downloadService('/my-service');
// bundle is a Buffer/Blob of the service bundle

database.getServiceReadme

async database.getServiceReadme(mount): string?

Retrieves the text content of the service's README or README.md file.

Returns undefined if no such file could be found.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const readme = await db.getServiceReadme('/my-service');
// readme is a string containing the service README's
// text content, or undefined if no README exists

database.getServiceDocumentation

async database.getServiceDocumentation(mount): Object

Retrieves a Swagger API description object for the service installed at the given mount point.

Arguments

mount: string

The service's mount point, relative to the database.

Examples

const spec = await db.getServiceDocumentation('/my-service');
// spec is a Swagger API description of the service

database.commitLocalServiceState

async database.commitLocalServiceState([replace]): void

Writes all locally available services to the database and updates any service bundles missing in the database.

Arguments

replace: boolean (Default: false)

Also commit outdated services.

This can be used to solve some consistency problems when service bundles are missing in the database or were deleted manually.

Examples

await db.commitLocalServiceState();
// all services available on the coordinator have been written to the db

// -- or --

await db.commitLocalServiceState(true);
// all service conflicts have been resolved in favor of this coordinator

HTTP Routes

Arbitrary HTTP routes

database.route

database.route([path,] [headers]): Route

Returns a new Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.

Arguments

path: string (optional)

The database-relative URL of the route.

headers: Object (optional)

Default headers that should be sent with each request to the route.

If path is missing, the route will refer to the base URL of the database.

For more information on Route instances see the Route API below.

Examples

const db = new Database();
const myFoxxService = db.route('my-foxx-service');
const response = await myFoxxService.post('users', {
  username: 'admin',
  password: 'hunter2'
});
// response.body is the result of
// POST /_db/_system/my-foxx-service/users
// with JSON request body '{"username": "admin", "password": "hunter2"}'

Collection

Collection API

These functions implement the HTTP API for manipulating collections.

The Collection API is implemented by all Collection instances, regardless of their specific type. I.e. it represents a shared subset between instances of DocumentCollection, EdgeCollection, GraphVertexCollection and GraphEdgeCollection.

Getting information about the collection

See the HTTP API documentation for details.

collection.exists

async collection.exists(): boolean

Checks whether the collection exists.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const result = await collection.exists();
// result indicates whether the collection exists

collection.get

async collection.get(): Object

Retrieves general information about the collection.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.get();
// data contains general information about the collection

collection.properties

async collection.properties(): Object

Retrieves the collection's properties.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.properties();
// data contains the collection's properties

collection.count

async collection.count(): Object

Retrieves information about the number of documents in a collection.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.count();
// data contains the collection's count

collection.figures

async collection.figures(): Object

Retrieves statistics for a collection.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.figures();
// data contains the collection's figures

collection.revision

async collection.revision(): Object

Retrieves the collection revision ID.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.revision();
// data contains the collection's revision

collection.checksum

async collection.checksum([opts]): Object

Retrieves the collection checksum.

Arguments

opts: Object (optional)

For information on the possible options see the HTTP API for getting collection information.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.checksum();
// data contains the collection's checksum

Collection Manipulation

Manipulating the collection

These functions implement the HTTP API for modifying collections.

collection.create

async collection.create([properties]): Object

Creates a collection with the given properties for this collection's name, then returns the server response.

Arguments

properties: Object (optional)

For more information on the properties object, see the HTTP API documentation for creating collections.

Examples

const db = new Database();
const collection = db.collection('potatoes');
await collection.create()
// the document collection "potatoes" now exists

// -- or --

const collection = db.edgeCollection('friends');
await collection.create({
  waitForSync: true // always sync document changes to disk
});
// the edge collection "friends" now exists

collection.load

async collection.load([count]): Object

Tells the server to load the collection into memory.

Arguments

count: boolean (Default: true)

If set to false, the return value will not include the number of documents in the collection (which may speed up the process).

Examples

const db = new Database();
const collection = db.collection('some-collection');
await collection.load(false)
// the collection has now been loaded into memory

collection.unload

async collection.unload(): Object

Tells the server to remove the collection from memory.

Examples

const db = new Database();
const collection = db.collection('some-collection');
await collection.unload()
// the collection has now been unloaded from memory

collection.setProperties

async collection.setProperties(properties): Object

Replaces the properties of the collection.

Arguments

properties: Object

For information on the properties argument see the HTTP API for modifying collections.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const result = await collection.setProperties({waitForSync: true})
assert.equal(result.waitForSync, true);
// the collection will now wait for data being written to disk
// whenever a document is changed

collection.rename

async collection.rename(name): Object

Renames the collection. The Collection instance will automatically update its name when the rename succeeds.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const result = await collection.rename('new-collection-name')
assert.equal(result.name, 'new-collection-name');
assert.equal(collection.name, result.name);
// result contains additional information about the collection

collection.rotate

async collection.rotate(): Object

Rotates the journal of the collection.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = await collection.rotate();
// data.result will be true if rotation succeeded

collection.truncate

async collection.truncate(): Object

Deletes all documents in the collection in the database.

Examples

const db = new Database();
const collection = db.collection('some-collection');
await collection.truncate();
// the collection "some-collection" is now empty

collection.drop

async collection.drop([properties]): Object

Deletes the collection from the database.

Arguments

properties: Object (optional)

An object with the following properties:

isSystem: Boolean (Default: false)

Whether the collection should be dropped even if it is a system collection.

This parameter must be set to true when dropping a system collection.

For more information on the properties object, see the HTTP API documentation for dropping collections. Examples

const db = new Database();
const collection = db.collection('some-collection');
await collection.drop();
// the collection "some-collection" no longer exists

Document Manipulation

Manipulating documents

These functions implement the HTTP API for manipulating documents.

collection.replace

async collection.replace(documentHandle, newValue, [opts]): Object

Replaces the content of the document with the given documentHandle with the given newValue and returns an object containing the document's metadata.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

documentHandle: string

The handle of the document to replace. This can either be the _id or the _key of a document in the collection, or a document (i.e. an object with an _id or _key property).

newValue: Object

The new data of the document.

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until the document has been synced to disk. Default: false.

rev: string (optional)

Only replace the document if it matches this revision.

policy: string (optional)

Determines the behaviour when the revision is not matched:

if policy is set to "last", the document will be replaced regardless of the revision.

if policy is set to "error" or not set, the replacement will fail with an error.

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const data = {number: 1, hello: 'world'};
const info1 = await collection.save(data);
const info2 = await collection.replace(info1, {number: 2});
assert.equal(info2._id, info1._id);
assert.notEqual(info2._rev, info1._rev);
const doc = await collection.document(info1);
assert.equal(doc._id, info1._id);
assert.equal(doc._rev, info2._rev);
assert.equal(doc.number, 2);
assert.equal(doc.hello, undefined);

collection.update

async collection.update(documentHandle, newValue, [opts]): Object

Updates (merges) the content of the document with the given documentHandle with the given newValue and returns an object containing the document's metadata.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

documentHandle: string

Handle of the document to update. This can be either the _id or the _key of a document in the collection, or a document (i.e. an object with an _id or _key property).

newValue: Object

The new data of the document.

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until document has been synced to disk.

keepNull: boolean (Default: true)

If set to false, properties with a value of null indicate that a property should be deleted.

mergeObjects: boolean (Default: true)

If set to false, object properties that already exist in the old document will be overwritten rather than merged. This does not affect arrays.

returnOld: boolean (Default: false)

If set to true, return additionally the complete previous revision of the changed documents under the attribute old in the result.

returnNew: boolean (Default: false)

If set to true, return additionally the complete new documents under the attribute new in the result.

ignoreRevs: boolean (Default: true)

By default, or if this is set to true, the _rev attributes in the given documents are ignored. If this is set to false, then any _rev attribute given in a body document is taken as a precondition. The document is only updated if the current revision is the one specified.

rev: string (optional)

Only update the document if it matches this revision.

policy: string (optional)

Determines the behaviour when the revision is not matched:

if policy is set to "last", the document will be replaced regardless of the revision.

if policy is set to "error" or not set, the replacement will fail with an error.

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const doc = {number: 1, hello: 'world'};
const doc1 = await collection.save(doc);
const doc2 = await collection.update(doc1, {number: 2});
assert.equal(doc2._id, doc1._id);
assert.notEqual(doc2._rev, doc1._rev);
const doc3 = await collection.document(doc2);
assert.equal(doc3._id, doc2._id);
assert.equal(doc3._rev, doc2._rev);
assert.equal(doc3.number, 2);
assert.equal(doc3.hello, doc.hello);

collection.bulkUpdate

async collection.bulkUpdate(documents, [opts]): Object

Updates (merges) the content of the documents with the given documents and returns an array containing the documents' metadata.

Note: This method is new in 3.0 and is available when using the driver with ArangoDB 3.0 and higher.

Arguments

documents: Array<Object>

Documents to update. Each object must have either the _id or the _key property.

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until document has been synced to disk.

keepNull: boolean (Default: true)

If set to false, properties with a value of null indicate that a property should be deleted.

mergeObjects: boolean (Default: true)

If set to false, object properties that already exist in the old document will be overwritten rather than merged. This does not affect arrays.

returnOld: boolean (Default: false)

If set to true, return additionally the complete previous revision of the changed documents under the attribute old in the result.

returnNew: boolean (Default: false)

If set to true, return additionally the complete new documents under the attribute new in the result.

ignoreRevs: boolean (Default: true)

By default, or if this is set to true, the _rev attributes in the given documents are ignored. If this is set to false, then any _rev attribute given in a body document is taken as a precondition. The document is only updated if the current revision is the one specified.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const doc1 = {number: 1, hello: 'world1'};
const info1 = await collection.save(doc1);
const doc2 = {number: 2, hello: 'world2'};
const info2 = await collection.save(doc2);
const result = await collection.bulkUpdate([
  {_key: info1._key, number: 3},
  {_key: info2._key, number: 4}
], {returnNew: true})

collection.remove

async collection.remove(documentHandle, [opts]): Object

Deletes the document with the given documentHandle from the collection.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

documentHandle: string

The handle of the document to delete. This can be either the _id or the _key of a document in the collection, or a document (i.e. an object with an _id or _key property).

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until document has been synced to disk.

rev: string (optional)

Only update the document if it matches this revision.

policy: string (optional)

Determines the behaviour when the revision is not matched:

if policy is set to "last", the document will be replaced regardless of the revision.

if policy is set to "error" or not set, the replacement will fail with an error.

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection('some-collection');

await collection.remove('some-doc');
// document 'some-collection/some-doc' no longer exists

// -- or --

await collection.remove('some-collection/some-doc');
// document 'some-collection/some-doc' no longer exists

collection.list

async collection.list([type]): Array<string>

Retrieves a list of references for all documents in the collection.

Arguments

type: string (Default: "id")

The format of the document references:

if type is set to "id", each reference will be the _id of the document.

if type is set to "key", each reference will be the _key of the document.

if type is set to "path", each reference will be the URI path of the document.

DocumentCollection

DocumentCollection API

The DocumentCollection API extends the Collection API with the following methods.

documentCollection.document

async documentCollection.document(documentHandle, [graceful]): Object

Retrieves the document with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the document to retrieve. This can be either the _id or the _key of a document in the collection, or a document (i.e. an object with an _id or _key property).

graceful: boolean (Default: false)

If set to true, the method will return null instead of throwing an error if the document does not exist.

Examples

const db = new Database();
const collection = db.collection('my-docs');

try {
  const doc = await collection.document('some-key');
  // the document exists
  assert.equal(doc._key, 'some-key');
  assert.equal(doc._id, 'my-docs/some-key');
} catch (err) {
  // something went wrong or
  // the document does not exist
}

// -- or --

try {
  const doc = await collection.document('my-docs/some-key');
  // the document exists
  assert.equal(doc._key, 'some-key');
  assert.equal(doc._id, 'my-docs/some-key');
} catch (err) {
  // something went wrong or
  // the document does not exist
}

// -- or --

const doc = await collection.document('some-key', true);
if (doc === null) {
  // the document does not exist
}

documentCollection.documentExists

async documentCollection.documentExists(documentHandle): boolean

Checks whether the document with the given documentHandle exists.

Arguments

documentHandle: string

The handle of the document to retrieve. This can be either the _id or the _key of a document in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const collection = db.collection('my-docs');

const exists = await collection.documentExists('some-key');
if (exists === false) {
  // the document does not exist
}

documentCollection.save

async documentCollection.save(data, [opts]): Object

Creates a new document with the given data and returns an object containing the document's metadata.

Arguments

data: Object

The data of the new document, may include a _key.

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until document has been synced to disk.

returnNew: boolean (Default: false)

If set to true, return additionally the complete new documents under the attribute new in the result.

returnOld: boolean (Default: false)

If set to true, return additionally the complete old documents under the attribute old in the result.

silent: boolean (Default: false)

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

overwrite: boolean (Default: false)

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

If a boolean is passed instead of an options object, it will be interpreted as the returnNew option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection('my-docs');
const data = {some: 'data'};
const info = await collection.save(data);
assert.equal(info._id, 'my-docs/' + info._key);
const doc2 = await collection.document(info)
assert.equal(doc2._id, info._id);
assert.equal(doc2._rev, info._rev);
assert.equal(doc2.some, data.some);

// -- or --

const db = new Database();
const collection = db.collection('my-docs');
const data = {some: 'data'};
const opts = {returnNew: true};
const doc = await collection.save(data, opts)
assert.equal(doc1._id, 'my-docs/' + doc1._key);
assert.equal(doc1.new.some, data.some);

EdgeCollection

EdgeCollection API

The EdgeCollection API extends the Collection API with the following methods.

edgeCollection.document

async edgeCollection.document(documentHandle, [graceful]): Object

Alias: edgeCollection.edge.

Retrieves the edge with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the edge to retrieve. This can be either the _id or the _key of an edge in the collection, or an edge (i.e. an object with an _id or _key property).

graceful: boolean (Default: false)

If set to true, the method will return null instead of throwing an error if the edge does not exist.

Examples

const db = new Database();
const collection = db.edgeCollection('edges');

const edge = await collection.document('some-key');
// the edge exists
assert.equal(edge._key, 'some-key');
assert.equal(edge._id, 'edges/some-key');

// -- or --

const edge = await collection.document('edges/some-key');
// the edge exists
assert.equal(edge._key, 'some-key');
assert.equal(edge._id, 'edges/some-key');

// -- or --

const edge = await collection.document('some-key', true);
if (edge === null) {
  // the edge does not exist
}

edgeCollection.documentExists

async edgeCollection.documentExists(documentHandle): boolean

Checks whether the edge with the given documentHandle exists.

Arguments

documentHandle: string

The handle of the edge to retrieve. This can be either the _id or the _key of a edge in the collection, or an edge (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const collection = db.edgeCollection('my-docs');

const exists = await collection.documentExists('some-key');
if (exists === false) {
  // the edge does not exist
}

edgeCollection.save

async edgeCollection.save(data, [fromId, toId]): Object

Creates a new edge between the documents fromId and toId with the given data and returns an object containing the edge's metadata.

Arguments

data: Object

The data of the new edge. If fromId and toId are not specified, the data needs to contain the properties _from and _to.

fromId: string (optional)

The handle of the start vertex of this edge. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

toId: string (optional)

The handle of the end vertex of this edge. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

opts: Object (optional)

If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until document has been synced to disk.

returnNew: boolean (Default: false)

If set to true, return additionally the complete new documents under the attribute new in the result.

returnOld: boolean (Default: false)

If set to true, return additionally the complete old documents under the attribute old in the result.

silent: boolean (Default: false)

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

overwrite: boolean (Default: false)

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

If a boolean is passed instead of an options object, it will be interpreted as the returnNew option.

Examples

const db = new Database();
const collection = db.edgeCollection('edges');
const data = {some: 'data'};

const info = await collection.save(
  data,
  'vertices/start-vertex',
  'vertices/end-vertex'
);
assert.equal(info._id, 'edges/' + info._key);
const edge = await collection.edge(edge)
assert.equal(edge._key, info._key);
assert.equal(edge._rev, info._rev);
assert.equal(edge.some, data.some);
assert.equal(edge._from, 'vertices/start-vertex');
assert.equal(edge._to, 'vertices/end-vertex');

// -- or --

const info = await collection.save({
  some: 'data',
  _from: 'verticies/start-vertex',
  _to: 'vertices/end-vertex'
});
// ...

edgeCollection.edges

async edgeCollection.edges(documentHandle): Array<Object>

Retrieves a list of all edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const collection = db.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
])
const edges = await collection.edges('vertices/a');
assert.equal(edges.length, 3);
assert.deepEqual(edges.map(edge => edge._key), ['x', 'y', 'z']);

edgeCollection.inEdges

async edgeCollection.inEdges(documentHandle): Array<Object>

Retrieves a list of all incoming edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const collection = db.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
]);
const edges = await collection.inEdges('vertices/a');
assert.equal(edges.length, 1);
assert.equal(edges[0]._key, 'z');

edgeCollection.outEdges

async edgeCollection.outEdges(documentHandle): Array<Object>

Retrieves a list of all outgoing edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const collection = db.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
]);
const edges = await collection.outEdges('vertices/a');
assert.equal(edges.length, 2);
assert.deepEqual(edges.map(edge => edge._key), ['x', 'y']);

edgeCollection.traversal

async edgeCollection.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in this edge collection.

Arguments

startVertex: string

The handle of the start vertex. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

opts: Object

See the HTTP API documentation for details on the additional arguments.

Please note that while opts.filter, opts.visitor, opts.init, opts.expander and opts.sort should be strings evaluating to well-formed JavaScript code, it's not possible to pass in JavaScript functions directly because the code needs to be evaluated on the server and will be transmitted in plain text.

Examples

const db = new Database();
const collection = db.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/b', 'vertices/c'],
  ['z', 'vertices/c', 'vertices/d']
]);
const result = await collection.traversal('vertices/a', {
  direction: 'outbound',
  visitor: 'result.vertices.push(vertex._key);',
  init: 'result.vertices = [];'
});
assert.deepEqual(result.vertices, ['a', 'b', 'c', 'd']);

Indexes

Manipulating indexes

These functions implement the HTTP API for manipulating indexes.

collection.createIndex

async collection.createIndex(details): Object

Creates an arbitrary index on the collection.

Arguments

details: Object

For information on the possible properties of the details object, see the HTTP API for manipulating indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const index = await collection.createIndex({type: 'hash', fields: ['a', 'a.b']});
// the index has been created with the handle `index.id`

collection.createHashIndex

async collection.createHashIndex(fields, [opts]): Object

Creates a hash index on the collection.

Arguments

fields: Array<string>

An array of names of document fields on which to create the index. If the value is a string, it will be wrapped in an array automatically.

opts: Object (optional)

Additional options for this index. If the value is a boolean, it will be interpreted as opts.unique.

For more information on hash indexes, see the HTTP API for hash indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createHashIndex('favorite-color');
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['favorite-color']);

// -- or --

const index = await collection.createHashIndex(['favorite-color']);
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['favorite-color']);

collection.createSkipList

async collection.createSkipList(fields, [opts]): Object

Creates a skiplist index on the collection.

Arguments

fields: Array<string>

An array of names of document fields on which to create the index. If the value is a string, it will be wrapped in an array automatically.

opts: Object (optional)

Additional options for this index. If the value is a boolean, it will be interpreted as opts.unique.

For more information on skiplist indexes, see the HTTP API for skiplist indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createSkipList('favorite-color')
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['favorite-color']);

// -- or --

const index = await collection.createSkipList(['favorite-color'])
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['favorite-color']);

collection.createGeoIndex

async collection.createGeoIndex(fields, [opts]): Object

Creates a geo-spatial index on the collection.

Arguments

fields: Array<string>

An array of names of document fields on which to create the index. Currently, geo indexes must cover exactly one field. If the value is a string, it will be wrapped in an array automatically.

opts: Object (optional)

An object containing additional properties of the index.

For more information on the properties of the opts object see the HTTP API for manipulating geo indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createGeoIndex(['latitude', 'longitude']);
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['longitude', 'latitude']);

// -- or --

const index = await collection.createGeoIndex('location', {geoJson: true});
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['location']);

collection.createFulltextIndex

async collection.createFulltextIndex(fields, [minLength]): Object

Creates a fulltext index on the collection.

Arguments

fields: Array<string>

An array of names of document fields on which to create the index. Currently, fulltext indexes must cover exactly one field. If the value is a string, it will be wrapped in an array automatically.

minLength (optional):

Minimum character length of words to index. Uses a server-specific default value if not specified.

For more information on fulltext indexes, see the HTTP API for fulltext indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createFulltextIndex('description');
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['description']);

// -- or --

const index = await collection.createFulltextIndex(['description']);
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['description']);

collection.createPersistentIndex

async collection.createPersistentIndex(fields, [opts]): Object

Creates a Persistent index on the collection. Persistent indexes are similarly in operation to skiplist indexes, only that these indexes are in disk as opposed to in memory. This reduces memory usage and DB startup time, with the trade-off being that it will always be orders of magnitude slower than in-memory indexes.

Arguments

fields: Array<string>

An array of names of document fields on which to create the index.

opts: Object (optional)

An object containing additional properties of the index.

For more information on the properties of the opts object see the HTTP API for manipulating Persistent indexes.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createPersistentIndex(['name', 'email']);
// the index has been created with the handle `index.id`
assert.deepEqual(index.fields, ['name', 'email']);

collection.index

async collection.index(indexHandle): Object

Fetches information about the index with the given indexHandle and returns it.

Arguments

indexHandle: string

The handle of the index to look up. This can either be a fully-qualified identifier or the collection-specific key of the index. If the value is an object, its id property will be used instead.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const index = await collection.createFulltextIndex('description');
const result = await collection.index(index.id);
assert.equal(result.id, index.id);
// result contains the properties of the index

// -- or --

const result = await collection.index(index.id.split('/')[1]);
assert.equal(result.id, index.id);
// result contains the properties of the index

collection.indexes

async collection.indexes(): Array<Object>

Fetches a list of all indexes on this collection.

Examples

const db = new Database();
const collection = db.collection('some-collection');
await collection.createFulltextIndex('description')
const indexes = await collection.indexes();
assert.equal(indexes.length, 1);
// indexes contains information about the index

collection.dropIndex

async collection.dropIndex(indexHandle): Object

Deletes the index with the given indexHandle from the collection.

Arguments

indexHandle: string

The handle of the index to delete. This can either be a fully-qualified identifier or the collection-specific key of the index. If the value is an object, its id property will be used instead.

Examples

const db = new Database();
const collection = db.collection('some-collection');
const index = await collection.createFulltextIndex('description');
await collection.dropIndex(index.id);
// the index has been removed from the collection

// -- or --

await collection.dropIndex(index.id.split('/')[1]);
// the index has been removed from the collection

collection.createCapConstraint

async collection.createCapConstraint(size): Object

Creates a cap constraint index on the collection.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as cap constraints are no longer supported.

Arguments

size: Object

An object with any of the following properties:

size: number (optional)

The maximum number of documents in the collection.

byteSize: number (optional)

The maximum size of active document data in the collection (in bytes).

If size is a number, it will be interpreted as size.size.

For more information on the properties of the size object see the HTTP API for creating cap constraints.

Examples

const db = new Database();
const collection = db.collection('some-collection');

const index = await collection.createCapConstraint(20)
// the index has been created with the handle `index.id`
assert.equal(index.size, 20);

// -- or --

const index = await collection.createCapConstraint({size: 20})
// the index has been created with the handle `index.id`
assert.equal(index.size, 20);

Simple Queries

Simple queries

These functions implement the HTTP API for simple queries.

collection.all

async collection.all([opts]): Cursor

Performs a query to fetch all documents in the collection. Returns a new Cursor instance for the query results.

Arguments

opts: Object (optional)

For information on the possible options see the HTTP API for returning all documents.

collection.any

async collection.any(): Object

Fetches a document from the collection at random.

collection.first

async collection.first([opts]): Array<Object>

Performs a query to fetch the first documents in the collection. Returns an array of the matching documents.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as the corresponding API method has been removed.

Arguments

opts: Object (optional)

For information on the possible options see the HTTP API for returning the first document of a collection.

If opts is a number it is treated as opts.count.

collection.last

async collection.last([opts]): Array<Object>

Performs a query to fetch the last documents in the collection. Returns an array of the matching documents.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as the corresponding API method has been removed.

Arguments

opts: Object (optional)

For information on the possible options see the HTTP API for returning the last document of a collection.

If opts is a number it is treated as opts.count.

collection.byExample

async collection.byExample(example, [opts]): Cursor

Performs a query to fetch all documents in the collection matching the given example. Returns a new Cursor instance for the query results.

Arguments

example: Object

An object representing an example for documents to be matched against.

opts: Object (optional)

For information on the possible options see the HTTP API for fetching documents by example.

collection.firstExample

async collection.firstExample(example): Object

Fetches the first document in the collection matching the given example.

Arguments

example: Object

An object representing an example for documents to be matched against.

collection.removeByExample

async collection.removeByExample(example, [opts]): Object

Removes all documents in the collection matching the given example.

Arguments

example: Object

An object representing an example for documents to be matched against.

opts: Object (optional)

For information on the possible options see the HTTP API for removing documents by example.

collection.replaceByExample

async collection.replaceByExample(example, newValue, [opts]): Object

Replaces all documents in the collection matching the given example with the given newValue.

Arguments

example: Object

An object representing an example for documents to be matched against.

newValue: Object

The new value to replace matching documents with.

opts: Object (optional)

For information on the possible options see the HTTP API for replacing documents by example.

collection.updateByExample

async collection.updateByExample(example, newValue, [opts]): Object

Updates (patches) all documents in the collection matching the given example with the given newValue.

Arguments

example: Object

An object representing an example for documents to be matched against.

newValue: Object

The new value to update matching documents with.

opts: Object (optional)

For information on the possible options see the HTTP API for updating documents by example.

collection.lookupByKeys

async collection.lookupByKeys(keys): Array<Object>

Fetches the documents with the given keys from the collection. Returns an array of the matching documents.

Arguments

keys: Array

An array of document keys to look up.

collection.removeByKeys

async collection.removeByKeys(keys, [opts]): Object

Deletes the documents with the given keys from the collection.

Arguments

keys: Array

An array of document keys to delete.

opts: Object (optional)

For information on the possible options see the HTTP API for removing documents by keys.

collection.fulltext

async collection.fulltext(fieldName, query, [opts]): Cursor

Performs a fulltext query in the given fieldName on the collection.

Arguments

fieldName: String

Name of the field to search on documents in the collection.

query: String

Fulltext query string to search for.

opts: Object (optional)

For information on the possible options see the HTTP API for fulltext queries.

Bulk Import

Bulk importing documents

This function implements the HTTP API for bulk imports.

collection.import

async collection.import(data, [opts]): Object

Bulk imports the given data into the collection.

Arguments

data: Array<Array<any>> | Array<Object>

The data to import. This can be an array of documents:

[
  {key1: value1, key2: value2}, // document 1
  {key1: value1, key2: value2}, // document 2
  ...
]

Or it can be an array of value arrays following an array of keys.

[
  ['key1', 'key2'], // key names
  [value1, value2], // document 1
  [value1, value2], // document 2
  ...
]

opts: Object (optional) If opts is set, it must be an object with any of the following properties:

waitForSync: boolean (Default: false)

Wait until the documents have been synced to disk.

details: boolean (Default: false)

Whether the response should contain additional details about documents that could not be imported.false*.

type: string (Default: "auto")

Indicates which format the data uses. Can be "documents", "array" or "auto".

If data is a JavaScript array, it will be transmitted as a line-delimited JSON stream. If opts.type is set to "array", it will be transmitted as regular JSON instead. If data is a string, it will be transmitted as it is without any processing.

For more information on the opts object, see the HTTP API documentation for bulk imports.

Examples

const db = new Database();
const collection = db.collection('users');

// document stream
const result = await collection.import([
  {username: 'admin', password: 'hunter2'},
  {username: 'jcd', password: 'bionicman'},
  {username: 'jreyes', password: 'amigo'},
  {username: 'ghermann', password: 'zeitgeist'}
]);
assert.equal(result.created, 4);

// -- or --

// array stream with header
const result = await collection.import([
  ['username', 'password'], // keys
  ['admin', 'hunter2'], // row 1
  ['jcd', 'bionicman'], // row 2
  ['jreyes', 'amigo'],
  ['ghermann', 'zeitgeist']
]);
assert.equal(result.created, 4);

// -- or --

// raw line-delimited JSON array stream with header
const result = await collection.import([
  '["username", "password"]',
  '["admin", "hunter2"]',
  '["jcd", "bionicman"]',
  '["jreyes", "amigo"]',
  '["ghermann", "zeitgeist"]'
].join('\r\n') + '\r\n');
assert.equal(result.created, 4);

View Manipulation

View API

These functions implement the HTTP API for manipulating views.

view.exists

async view.exists(): boolean

Checks whether the view exists.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const result = await view.exists();
// result indicates whether the view exists

view.get

async view.get(): Object

Retrieves general information about the view.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const data = await view.get();
// data contains general information about the view

view.properties

async view.properties(): Object

Retrieves the view's properties.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const data = await view.properties();
// data contains the view's properties

view.create

async view.create([properties]): Object

Creates a view with the given properties for this view's name, then returns the server response.

Arguments

properties: Object (optional)

For more information on the properties object, see the HTTP API documentation for creating views.

Examples

const db = new Database();
const view = db.arangoSearchView('potatoes');
await view.create()
// the arangosearch view "potatoes" now exists

view.setProperties

async view.setProperties(properties): Object

Updates the properties of the view.

Arguments

properties: Object

For information on the properties argument see the HTTP API for modifying views.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const result = await view.setProperties({ locale: "C" })
assert.equal(result.locale, "C");

view.replaceProperties

async view.replaceProperties(properties): Object

Replaces the properties of the view.

Arguments

properties: Object

For information on the properties argument see the HTTP API for modifying views.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const result = await view.replaceProperties({ locale: "C" })
assert.equal(result.locale, "C");

view.rename

async view.rename(name): Object

Renames the view. The View instance will automatically update its name when the rename succeeds.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
const result = await view.rename('new-view-name')
assert.equal(result.name, 'new-view-name');
assert.equal(view.name, result.name);
// result contains additional information about the view

view.drop

async view.drop(): Object

Deletes the view from the database.

Examples

const db = new Database();
const view = db.arangoSearchView('some-view');
await view.drop();
// the view "some-view" no longer exists

Cursor

Cursor API

Cursor instances provide an abstraction over the HTTP API's limitations. Unless a method explicitly exhausts the cursor, the driver will only fetch as many batches from the server as necessary. Like the server-side cursors, Cursor instances are incrementally depleted as they are read from.

const db = new Database();
const cursor = await db.query('FOR x IN 1..5 RETURN x');
// query result list: [1, 2, 3, 4, 5]
const value = await cursor.next();
assert.equal(value, 1);
// remaining result list: [2, 3, 4, 5]

cursor.count

cursor.count: number

The total number of documents in the query result. This is only available if the count option was used.

cursor.all

async cursor.all(): Array<Object>

Exhausts the cursor, then returns an array containing all values in the cursor's remaining result list.

Examples

const cursor = await db._query('FOR x IN 1..5 RETURN x');
const result = await cursor.all()
// result is an array containing the entire query result
assert.deepEqual(result, [1, 2, 3, 4, 5]);
assert.equal(cursor.hasNext(), false);

cursor.next

async cursor.next(): Object

Advances the cursor and returns the next value in the cursor's remaining result list. If the cursor has already been exhausted, returns undefined instead.

Examples

// query result list: [1, 2, 3, 4, 5]
const val = await cursor.next();
assert.equal(val, 1);
// remaining result list: [2, 3, 4, 5]

const val2 = await cursor.next();
assert.equal(val2, 2);
// remaining result list: [3, 4, 5]

cursor.hasNext

cursor.hasNext(): boolean

Returns true if the cursor has more values or false if the cursor has been exhausted.

Examples

await cursor.all(); // exhausts the cursor
assert.equal(cursor.hasNext(), false);

cursor.each

async cursor.each(fn): any

Advances the cursor by applying the function fn to each value in the cursor's remaining result list until the cursor is exhausted or fn explicitly returns false.

Returns the last return value of fn.

Equivalent to Array.prototype.forEach (except async).

Arguments

fn: Function

A function that will be invoked for each value in the cursor's remaining result list until it explicitly returns false or the cursor is exhausted.

The function receives the following arguments:

value: any

The value in the cursor's remaining result list.

index: number

The index of the value in the cursor's remaining result list.

cursor: Cursor

The cursor itself.

Examples

const results = [];
function doStuff(value) {
  const VALUE = value.toUpperCase();
  results.push(VALUE);
  return VALUE;
}

const cursor = await db.query('FOR x IN ["a", "b", "c"] RETURN x')
const last = await cursor.each(doStuff);
assert.deepEqual(results, ['A', 'B', 'C']);
assert.equal(cursor.hasNext(), false);
assert.equal(last, 'C');

cursor.every

async cursor.every(fn): boolean

Advances the cursor by applying the function fn to each value in the cursor's remaining result list until the cursor is exhausted or fn returns a value that evaluates to false.

Returns false if fn returned a value that evaluates to false, or true otherwise.

Equivalent to Array.prototype.every (except async).

Arguments

fn: Function

A function that will be invoked for each value in the cursor's remaining result list until it returns a value that evaluates to false or the cursor is exhausted.

The function receives the following arguments:

value: any

The value in the cursor's remaining result list.

index: number

The index of the value in the cursor's remaining result list.

cursor: Cursor

The cursor itself.

const even = value => value % 2 === 0;

const cursor = await db.query('FOR x IN 2..5 RETURN x');
const result = await cursor.every(even);
assert.equal(result, false); // 3 is not even
assert.equal(cursor.hasNext(), true);

const value = await cursor.next();
assert.equal(value, 4); // next value after 3

cursor.some

async cursor.some(fn): boolean

Advances the cursor by applying the function fn to each value in the cursor's remaining result list until the cursor is exhausted or fn returns a value that evaluates to true.

Returns true if fn returned a value that evalutes to true, or false otherwise.

Equivalent to Array.prototype.some (except async).

Examples

const even = value => value % 2 === 0;

const cursor = await db.query('FOR x IN 1..5 RETURN x');
const result = await cursor.some(even);
assert.equal(result, true); // 2 is even
assert.equal(cursor.hasNext(), true);

const value = await cursor.next();
assert.equal(value, 3); // next value after 2

cursor.map

cursor.map(fn): Array<any>

Advances the cursor by applying the function fn to each value in the cursor's remaining result list until the cursor is exhausted.

Returns an array of the return values of fn.

Equivalent to Array.prototype.map (except async).

Note: This creates an array of all return values. It is probably a bad idea to do this for very large query result sets.

Arguments

fn: Function

A function that will be invoked for each value in the cursor's remaining result list until the cursor is exhausted.

The function receives the following arguments:

value: any

The value in the cursor's remaining result list.

index: number

The index of the value in the cursor's remaining result list.

cursor: Cursor

The cursor itself.

Examples

const square = value => value * value;
const cursor = await db.query('FOR x IN 1..5 RETURN x');
const result = await cursor.map(square);
assert.equal(result.length, 5);
assert.deepEqual(result, [1, 4, 9, 16, 25]);
assert.equal(cursor.hasNext(), false);

cursor.reduce

cursor.reduce(fn, [accu]): any

Exhausts the cursor by reducing the values in the cursor's remaining result list with the given function fn. If accu is not provided, the first value in the cursor's remaining result list will be used instead (the function will not be invoked for that value).

Equivalent to Array.prototype.reduce (except async).

Arguments

fn: Function

A function that will be invoked for each value in the cursor's remaining result list until the cursor is exhausted.

The function receives the following arguments:

accu: any

The return value of the previous call to fn. If this is the first call, accu will be set to the accu value passed to reduce or the first value in the cursor's remaining result list.

value: any

The value in the cursor's remaining result list.

index: number

The index of the value in the cursor's remaining result list.

cursor: Cursor

The cursor itself.

Examples

const add = (a, b) => a + b;
const baseline = 1000;

const cursor = await db.query('FOR x IN 1..5 RETURN x');
const result = await cursor.reduce(add, baseline)
assert.equal(result, baseline + 1 + 2 + 3 + 4 + 5);
assert.equal(cursor.hasNext(), false);

// -- or --

const result = await cursor.reduce(add);
assert.equal(result, 1 + 2 + 3 + 4 + 5);
assert.equal(cursor.hasNext(), false);

Graph

Graph API

These functions implement the HTTP API for manipulating graphs.

graph.exists

async graph.exists(): boolean

Checks whether the graph exists.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const result = await graph.exists();
// result indicates whether the graph exists

graph.get

async graph.get(): Object

Retrieves general information about the graph.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const data = await graph.get();
// data contains general information about the graph

graph.create

async graph.create(properties): Object

Creates a graph with the given properties for this graph's name, then returns the server response.

Arguments

properties: Object

For more information on the properties object, see the HTTP API documentation for creating graphs.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const info = await graph.create({
  edgeDefinitions: [{
    collection: 'edges',
    from: ['start-vertices'],
    to: ['end-vertices']
  }]
});
// graph now exists

graph.drop

async graph.drop([dropCollections]): Object

Deletes the graph from the database.

Arguments

dropCollections: boolean (optional)

If set to true, the collections associated with the graph will also be deleted.

Examples

const db = new Database();
const graph = db.graph('some-graph');
await graph.drop();
// the graph "some-graph" no longer exists

Vertices

Manipulating vertices

graph.vertexCollection

graph.vertexCollection(collectionName): GraphVertexCollection

Returns a new GraphVertexCollection instance with the given name for this graph.

Arguments

collectionName: string

Name of the vertex collection.

Examples

const db = new Database();
const graph = db.graph("some-graph");
const collection = graph.vertexCollection("vertices");
assert.equal(collection.name, "vertices");
// collection is a GraphVertexCollection

graph.listVertexCollections

async graph.listVertexCollections([excludeOrphans]): Array<Object>

Fetches all vertex collections from the graph and returns an array of collection descriptions.

Arguments

excludeOrphans: boolean (Default: false)

Whether orphan collections should be excluded.

Examples

const graph = db.graph('some-graph');

const collections = await graph.listVertexCollections();
// collections is an array of collection descriptions
// including orphan collections

// -- or --

const collections = await graph.listVertexCollections(true);
// collections is an array of collection descriptions
// not including orphan collections

graph.vertexCollections

async graph.vertexCollections([excludeOrphans]): Array<Collection>

Fetches all vertex collections from the database and returns an array of GraphVertexCollection instances for the collections.

Arguments

excludeOrphans: boolean (Default: false)

Whether orphan collections should be excluded.

Examples

const graph = db.graph('some-graph');

const collections = await graph.vertexCollections()
// collections is an array of GraphVertexCollection
// instances including orphan collections

// -- or --

const collections = await graph.vertexCollections(true)
// collections is an array of GraphVertexCollection
// instances not including orphan collections

graph.addVertexCollection

async graph.addVertexCollection(collectionName): Object

Adds the collection with the given collectionName to the graph's vertex collections.

Arguments

collectionName: string

Name of the vertex collection to add to the graph.

Examples

const db = new Database();
const graph = db.graph('some-graph');
await graph.addVertexCollection('vertices');
// the collection "vertices" has been added to the graph

graph.removeVertexCollection

async graph.removeVertexCollection(collectionName, [dropCollection]): Object

Removes the vertex collection with the given collectionName from the graph.

Arguments

collectionName: string

Name of the vertex collection to remove from the graph.

dropCollection: boolean (optional)

If set to true, the collection will also be deleted from the database.

Examples

const db = new Database();
const graph = db.graph('some-graph');
await graph.removeVertexCollection('vertices')
// collection "vertices" has been removed from the graph

// -- or --

await graph.removeVertexCollection('vertices', true)
// collection "vertices" has been removed from the graph
// the collection has also been dropped from the database
// this may have been a bad idea

Edges

Manipulating edges

graph.edgeCollection

graph.edgeCollection(collectionName): GraphEdgeCollection

Returns a new GraphEdgeCollection instance with the given name bound to this graph.

Arguments

collectionName: string

Name of the edge collection.

Examples

const db = new Database();
// assuming the collections "edges" and "vertices" exist
const graph = db.graph("some-graph");
const collection = graph.edgeCollection("edges");
assert.equal(collection.name, "edges");
// collection is a GraphEdgeCollection

graph.addEdgeDefinition

async graph.addEdgeDefinition(definition): Object

Adds the given edge definition definition to the graph.

Arguments

definition: Object

For more information on edge definitions see the HTTP API for managing graphs.

Examples

const db = new Database();
// assuming the collections "edges" and "vertices" exist
const graph = db.graph('some-graph');
await graph.addEdgeDefinition({
  collection: 'edges',
  from: ['vertices'],
  to: ['vertices']
});
// the edge definition has been added to the graph

graph.replaceEdgeDefinition

async graph.replaceEdgeDefinition(collectionName, definition): Object

Replaces the edge definition for the edge collection named collectionName with the given definition.

Arguments

collectionName: string

Name of the edge collection to replace the definition of.

definition: Object

For more information on edge definitions see the HTTP API for managing graphs.

Examples

const db = new Database();
// assuming the collections "edges", "vertices" and "more-vertices" exist
const graph = db.graph('some-graph');
await graph.replaceEdgeDefinition('edges', {
  collection: 'edges',
  from: ['vertices'],
  to: ['more-vertices']
});
// the edge definition has been modified

graph.removeEdgeDefinition

async graph.removeEdgeDefinition(definitionName, [dropCollection]): Object

Removes the edge definition with the given definitionName form the graph.

Arguments

definitionName: string

Name of the edge definition to remove from the graph.

dropCollection: boolean (optional)

If set to true, the edge collection associated with the definition will also be deleted from the database.

Examples

const db = new Database();
const graph = db.graph('some-graph');

await graph.removeEdgeDefinition('edges')
// the edge definition has been removed

// -- or --

await graph.removeEdgeDefinition('edges', true)
// the edge definition has been removed
// and the edge collection "edges" has been dropped
// this may have been a bad idea

graph.traversal

async graph.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in any of the edge collections of this graph.

Arguments

startVertex: string

The handle of the start vertex. This can be either the _id of a document in the graph or a document (i.e. an object with an _id property).

opts: Object

See the HTTP API documentation for details on the additional arguments.

Please note that while opts.filter, opts.visitor, opts.init, opts.expander and opts.sort should be strings evaluating to well-formed JavaScript functions, it's not possible to pass in JavaScript functions directly because the functions need to be evaluated on the server and will be transmitted in plain text.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/b', 'vertices/c'],
  ['z', 'vertices/c', 'vertices/d']
])
const result = await graph.traversal('vertices/a', {
  direction: 'outbound',
  visitor: 'result.vertices.push(vertex._key);',
  init: 'result.vertices = [];'
});
assert.deepEqual(result.vertices, ['a', 'b', 'c', 'd']);

VertexCollection

GraphVertexCollection API

The GraphVertexCollection API extends the Collection API with the following methods.

graphVertexCollection.remove

async graphVertexCollection.remove(documentHandle): Object

Deletes the vertex with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the vertex to retrieve. This can be either the _id or the _key of a vertex in the collection, or a vertex (i.e. an object with an _id or _key property).

Examples

const graph = db.graph('some-graph');
const collection = graph.vertexCollection('vertices');

await collection.remove('some-key')
// document 'vertices/some-key' no longer exists

// -- or --

await collection.remove('vertices/some-key')
// document 'vertices/some-key' no longer exists

graphVertexCollection.documentExists

async graphVertexCollection.documentExists(documentHandle): boolean

Checks whether the vertex with the given documentHandle exists.

Arguments

documentHandle: string

The handle of the vertex to retrieve. This can be either the _id or the _key of a vertex in the collection, or a vertex (i.e. an object with an _id or _key property).

Examples

const graph = db.graph('some-graph');
const collection = graph.vertexCollection('vertices');

const exists = await collection.documentExists('some-key');
if (exists === false) {
  // the vertex does not exist
}

graphVertexCollection.document

async graphVertexCollection.document(documentHandle, [graceful]): Object

Alias: graphVertexCollection.vertex.

Retrieves the vertex with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the vertex to retrieve. This can be either the _id or the _key of a vertex in the collection, or a vertex (i.e. an object with an _id or _key property).

graceful: boolean (Default: false)

If set to true, the method will return null instead of throwing an error if the vertex does not exist.

Examples

const graph = db.graph('some-graph');
const collection = graph.vertexCollection('vertices');

const doc = await collection.document('some-key');
// the vertex exists
assert.equal(doc._key, 'some-key');
assert.equal(doc._id, 'vertices/some-key');

// -- or --

const doc = await collection.document('vertices/some-key');
// the vertex exists
assert.equal(doc._key, 'some-key');
assert.equal(doc._id, 'vertices/some-key');

// -- or --

const doc = await collection.vertex('some-key', true);
if (doc === null) {
  // the vertex does not exist
}

graphVertexCollection.save

async graphVertexCollection.save(data): Object

Creates a new vertex with the given data.

Arguments

data: Object

The data of the vertex.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.vertexCollection('vertices');
const doc = await collection.save({some: 'data'});
assert.equal(doc._id, 'vertices/' + doc._key);
assert.equal(doc.some, 'data');

EdgeCollection

GraphEdgeCollection API

The GraphEdgeCollection API extends the Collection API with the following methods.

graphEdgeCollection.remove

async graphEdgeCollection.remove(documentHandle): Object

Deletes the edge with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the edge to retrieve. This can be either the _id or the _key of an edge in the collection, or an edge (i.e. an object with an _id or _key property).

Examples

const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');

await collection.remove('some-key')
// document 'edges/some-key' no longer exists

// -- or --

await collection.remove('edges/some-key')
// document 'edges/some-key' no longer exists

graphEdgeCollection.documentExists

async graphEdgeCollection.documentExists(documentHandle): boolean

Checks whether the edge with the given documentHandle exists.

Arguments

documentHandle: string

The handle of the edge to retrieve. This can be either the _id or the _key of a edge in the collection, or an edge (i.e. an object with an _id or _key property).

Examples

const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');

const exists = await collection.documentExists('some-key');
if (exists === false) {
  // the edge does not exist
}

graphEdgeCollection.document

async graphEdgeCollection.document(documentHandle, [graceful]): Object

Alias: graphEdgeCollection.edge.

Retrieves the edge with the given documentHandle from the collection.

Arguments

documentHandle: string

The handle of the edge to retrieve. This can be either the _id or the _key of an edge in the collection, or an edge (i.e. an object with an _id or _key property).

graceful: boolean (Default: false)

If set to true, the method will return null instead of throwing an error if the edge does not exist.

Examples

const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');

const edge = await collection.document('some-key');
// the edge exists
assert.equal(edge._key, 'some-key');
assert.equal(edge._id, 'edges/some-key');

// -- or --

const edge = await collection.document('edges/some-key');
// the edge exists
assert.equal(edge._key, 'some-key');
assert.equal(edge._id, 'edges/some-key');

// -- or --

const edge = await collection.document('some-key', true);
if (edge === null) {
  // the edge does not exist
}

graphEdgeCollection.save

async graphEdgeCollection.save(data, [fromId, toId]): Object

Creates a new edge between the vertices fromId and toId with the given data.

Arguments

data: Object

The data of the new edge. If fromId and toId are not specified, the data needs to contain the properties from_ and to_.

fromId: string (optional)

The handle of the start vertex of this edge. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

toId: string (optional)

The handle of the end vertex of this edge. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
const edge = await collection.save(
  {some: 'data'},
  'vertices/start-vertex',
  'vertices/end-vertex'
);
assert.equal(edge._id, 'edges/' + edge._key);
assert.equal(edge.some, 'data');
assert.equal(edge._from, 'vertices/start-vertex');
assert.equal(edge._to, 'vertices/end-vertex');

graphEdgeCollection.edges

async graphEdgeCollection.edges(documentHandle): Array<Object>

Retrieves a list of all edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
]);
const edges = await collection.edges('vertices/a');
assert.equal(edges.length, 3);
assert.deepEqual(edges.map(edge => edge._key), ['x', 'y', 'z']);

graphEdgeCollection.inEdges

async graphEdgeCollection.inEdges(documentHandle): Array<Object>

Retrieves a list of all incoming edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
]);
const edges = await collection.inEdges('vertices/a');
assert.equal(edges.length, 1);
assert.equal(edges[0]._key, 'z');

graphEdgeCollection.outEdges

async graphEdgeCollection.outEdges(documentHandle): Array<Object>

Retrieves a list of all outgoing edges of the document with the given documentHandle.

Arguments

documentHandle: string

The handle of the document to retrieve the edges of. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/a', 'vertices/c'],
  ['z', 'vertices/d', 'vertices/a']
]);
const edges = await collection.outEdges('vertices/a');
assert.equal(edges.length, 2);
assert.deepEqual(edges.map(edge => edge._key), ['x', 'y']);

graphEdgeCollection.traversal

async graphEdgeCollection.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in this edge collection.

Arguments

startVertex: string

The handle of the start vertex. This can be either the _id of a document in the database, the _key of an edge in the collection, or a document (i.e. an object with an _id or _key property).

opts: Object

See the HTTP API documentation for details on the additional arguments.

Please note that while opts.filter, opts.visitor, opts.init, opts.expander and opts.sort should be strings evaluating to well-formed JavaScript code, it's not possible to pass in JavaScript functions directly because the code needs to be evaluated on the server and will be transmitted in plain text.

Examples

const db = new Database();
const graph = db.graph('some-graph');
const collection = graph.edgeCollection('edges');
await collection.import([
  ['_key', '_from', '_to'],
  ['x', 'vertices/a', 'vertices/b'],
  ['y', 'vertices/b', 'vertices/c'],
  ['z', 'vertices/c', 'vertices/d']
]);
const result = await collection.traversal('vertices/a', {
  direction: 'outbound',
  visitor: 'result.vertices.push(vertex._key);',
  init: 'result.vertices = [];'
});
assert.deepEqual(result.vertices, ['a', 'b', 'c', 'd']);

Route

Route API

Route instances provide access for arbitrary HTTP requests. This allows easy access to Foxx services and other HTTP APIs not covered by the driver itself.

route.route

route.route([path], [headers]): Route

Returns a new Route instance for the given path (relative to the current route) that can be used to perform arbitrary HTTP requests.

Arguments

path: string (optional)

The relative URL of the route.

headers: Object (optional)

Default headers that should be sent with each request to the route.

If path is missing, the route will refer to the base URL of the database.

Examples

const db = new Database();
const route = db.route("my-foxx-service");
const users = route.route("users");
// equivalent to db.route('my-foxx-service/users')

route.get

async route.get([path,] [qs]): Response

Performs a GET request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.get();
// response.body is the response body of calling
// GET _db/_system/my-foxx-service

// -- or --

const response = await route.get('users');
// response.body is the response body of calling
// GET _db/_system/my-foxx-service/users

// -- or --

const response = await route.get('users', {group: 'admin'});
// response.body is the response body of calling
// GET _db/_system/my-foxx-service/users?group=admin

route.post

async route.post([path,] [body, [qs]]): Response

Performs a POST request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

body: string (optional)

The response body. If body is an object, it will be encoded as JSON.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.post()
// response.body is the response body of calling
// POST _db/_system/my-foxx-service

// -- or --

const response = await route.post('users')
// response.body is the response body of calling
// POST _db/_system/my-foxx-service/users

// -- or --

const response = await route.post('users', {
  username: 'admin',
  password: 'hunter2'
});
// response.body is the response body of calling
// POST _db/_system/my-foxx-service/users
// with JSON request body {"username": "admin", "password": "hunter2"}

// -- or --

const response = await route.post('users', {
  username: 'admin',
  password: 'hunter2'
}, {admin: true});
// response.body is the response body of calling
// POST _db/_system/my-foxx-service/users?admin=true
// with JSON request body {"username": "admin", "password": "hunter2"}

route.put

async route.put([path,] [body, [qs]]): Response

Performs a PUT request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

body: string (optional)

The response body. If body is an object, it will be encoded as JSON.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.put();
// response.body is the response body of calling
// PUT _db/_system/my-foxx-service

// -- or --

const response = await route.put('users/admin');
// response.body is the response body of calling
// PUT _db/_system/my-foxx-service/users

// -- or --

const response = await route.put('users/admin', {
  username: 'admin',
  password: 'hunter2'
});
// response.body is the response body of calling
// PUT _db/_system/my-foxx-service/users/admin
// with JSON request body {"username": "admin", "password": "hunter2"}

// -- or --

const response = await route.put('users/admin', {
  username: 'admin',
  password: 'hunter2'
}, {admin: true});
// response.body is the response body of calling
// PUT _db/_system/my-foxx-service/users/admin?admin=true
// with JSON request body {"username": "admin", "password": "hunter2"}

route.patch

async route.patch([path,] [body, [qs]]): Response

Performs a PATCH request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

body: string (optional)

The response body. If body is an object, it will be encoded as JSON.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.patch();
// response.body is the response body of calling
// PATCH _db/_system/my-foxx-service

// -- or --

const response = await route.patch('users/admin');
// response.body is the response body of calling
// PATCH _db/_system/my-foxx-service/users

// -- or --

const response = await route.patch('users/admin', {
  password: 'hunter2'
});
// response.body is the response body of calling
// PATCH _db/_system/my-foxx-service/users/admin
// with JSON request body {"password": "hunter2"}

// -- or --

const response = await route.patch('users/admin', {
  password: 'hunter2'
}, {admin: true});
// response.body is the response body of calling
// PATCH _db/_system/my-foxx-service/users/admin?admin=true
// with JSON request body {"password": "hunter2"}

route.delete

async route.delete([path,] [qs]): Response

Performs a DELETE request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.delete()
// response.body is the response body of calling
// DELETE _db/_system/my-foxx-service

// -- or --

const response = await route.delete('users/admin')
// response.body is the response body of calling
// DELETE _db/_system/my-foxx-service/users/admin

// -- or --

const response = await route.delete('users/admin', {permanent: true})
// response.body is the response body of calling
// DELETE _db/_system/my-foxx-service/users/admin?permanent=true

route.head

async route.head([path,] [qs]): Response

Performs a HEAD request to the given URL and returns the server response.

Arguments

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.head();
// response is the response object for
// HEAD _db/_system/my-foxx-service

route.request

async route.request([opts]): Response

Performs an arbitrary request to the given URL and returns the server response.

Arguments

opts: Object (optional)

An object with any of the following properties:

path: string (optional)

The route-relative URL for the request. If omitted, the request will be made to the base URL of the route.

absolutePath: boolean (Default: false)

Whether the path is relative to the connection's base URL instead of the route.

body: string (optional)

The response body. If body is an object, it will be encoded as JSON.

qs: string (optional)

The query string for the request. If qs is an object, it will be translated to a query string.

headers: Object (optional)

An object containing additional HTTP headers to be sent with the request.

method: string (Default: "GET")

HTTP method of this request.

Examples

const db = new Database();
const route = db.route('my-foxx-service');
const response = await route.request({
  path: 'hello-world',
  method: 'POST',
  body: {hello: 'world'},
  qs: {admin: true}
});
// response.body is the response body of calling
// POST _db/_system/my-foxx-service/hello-world?admin=true
// with JSON request body '{"hello": "world"}'

ArangoDB-PHP

ArangoDB-PHP - A PHP client for ArangoDB

The official ArangoDB PHP Driver.

Getting Started

Tutorial

Changelog

More information

Check the ArangoDB PHP client on github.com regularly for new releases and updates: https://github.com/arangodb/arangodb-php

More example code, containing some code to create, delete and rename collections, is provided in the examples subdirectory that is provided with the library.

PHPDoc documentation for the complete library

Follow us on Twitter @arangodbphp to receive updates on the PHP driver

Getting Started

ArangoDB-PHP - Getting Started

Description

This PHP client allows REST-based access to documents on the server. The DocumentHandler class should be used for these purposes. There is an example for REST-based documents access in the file examples/document.php.

Furthermore, the PHP client also allows to issue more AQL complex queries using the Statement class. There is an example for this kind of statements in the file examples/select.php.

To use the PHP client, you must include the file autoloader.php from the main directory. The autoloader will care about loading additionally required classes on the fly. The autoloader can be nested with other autoloaders.

The ArangoDB PHP client is an API that allows you to send and retrieve documents from ArangoDB from out of your PHP application. The client library itself is written in PHP and has no further dependencies but just plain PHP 5.6 (or higher).

The client library provides document and collection classes you can use to work with documents and collections in an OO fashion. When exchanging document data with the server, the library internally will use the HTTP REST interface of ArangoDB. The library user does not have to care about this fact as all the details of the REST interface are abstracted by the client library.

Requirements

PHP version 5.6 or higher (Travis-tested with PHP 5.6, 7.0, 7.1 and hhvm)

Note on PHP version support:

This driver will cease to support old PHP versions as soon as they have reached end-of-life status. Support will be removed with the next minor or patch version of the driver to be released.

In general, it is recommended to always use the latest PHP versions (currently those in the PHP 7 line) in order to take advantage of all the improvements (especially in performance).

Important version information on ArangoDB-PHP

The ArangoDB-PHP driver version has to match with the ArangoDB version:

ArangoDB-PHP 3.1.x is on par with the functionality of ArangoDB 3.1.x

ArangoDB-PHP 3.2.x is on par with the functionality of ArangoDB 3.2.x

ArangoDB-PHP 3.3.x is on par with the functionality of ArangoDB 3.3.x

etc...

Installing the PHP client

To get started you need PHP 5.6 or higher plus an ArangoDB server running on any host that you can access.

There are two alternative ways to get the ArangoDB PHP client:

Using Composer

Cloning the git repository

Alternative 1: Using Composer

composer require triagens/arangodb

Alternative 2: Cloning the git repository

When preferring this alternative, you need to have a git client installed. To clone the ArangoDB PHP client repository from github, execute the following command in your project directory:

git clone "https://github.com/arangodb/arangodb-php.git"

This will create a subdirectory arangodb-php in your current directory. It contains all the files of the client library. It also includes a dedicated autoloader that you can use for autoloading the client libraries class files. To invoke this autoloader, add the following line to your PHP files that will use the library:

require 'arangodb-php/autoload.php';

The ArangoDB PHP client's autoloader will only care about its own class files and will not handle any other files. That means it is fully nestable with other autoloaders.

Alternative 3: Invoking the autoloader directly

If you do not wish to include autoload.php to load and setup the autoloader, you can invoke the autoloader directly:

require 'arangodb-php/lib/ArangoDBClient/autoloader.php';
\ArangoDBClient\Autoloader::init();

Tutorial

ArangoDB-PHP - Tutorial

Setting up the connection options

In order to use ArangoDB, you need to specify the connection options. We do so by creating a PHP array $connectionOptions. Put this code into a file named test.php in your current directory:

// use the following line when using Composer
// require __DIR__ . '/vendor/composer/autoload.php';

// use the following line when using git
require __DIR__ . '/arangodb-php/autoload.php';

// set up some aliases for less typing later
use ArangoDBClient\Collection as ArangoCollection;
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler;
use ArangoDBClient\Connection as ArangoConnection;
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions;
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler;
use ArangoDBClient\Document as ArangoDocument;
use ArangoDBClient\Exception as ArangoException;
use ArangoDBClient\Export as ArangoExport;
use ArangoDBClient\ConnectException as ArangoConnectException;
use ArangoDBClient\ClientException as ArangoClientException;
use ArangoDBClient\ServerException as ArangoServerException;
use ArangoDBClient\Statement as ArangoStatement;
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy;

// set up some basic connection options
$connectionOptions = [
    // database name
    ArangoConnectionOptions::OPTION_DATABASE => '_system',
    // server endpoint to connect to
    ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://127.0.0.1:8529',
    // authorization type to use (currently supported: 'Basic')
    ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
    // user for basic authorization
    ArangoConnectionOptions::OPTION_AUTH_USER => 'root',
    // password for basic authorization
    ArangoConnectionOptions::OPTION_AUTH_PASSWD => '',
    // connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
    ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive',
    // connect timeout in seconds
    ArangoConnectionOptions::OPTION_TIMEOUT => 3,
    // whether or not to reconnect when a keep-alive connection has timed out on server
    ArangoConnectionOptions::OPTION_RECONNECT => true,
    // optionally create new collections when inserting documents
    ArangoConnectionOptions::OPTION_CREATE => true,
    // optionally create new collections when inserting documents
    ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];

// turn on exception logging (logs to whatever PHP is configured)
ArangoException::enableLogging();

    $connection = new ArangoConnection($connectionOptions);

This will make the client connect to ArangoDB

running on localhost (OPTION_HOST)

on the default port 8529 (OPTION_PORT)

with a connection timeout of 3 seconds (OPTION_TIMEOUT)

When creating new documents in a collection that does not yet exist, you have the following choices:

auto-generate a new collection: if you prefer that, set OPTION_CREATE to true

fail with an error: if you prefer this behavior, set OPTION_CREATE to false

When updating a document that was previously/concurrently updated by another user, you can select between the following behaviors:

last update wins: if you prefer this, set OPTION_UPDATE_POLICY to last

fail with a conflict error: if you prefer that, set OPTION_UPDATE_POLICY to conflict

Setting up active failover

By default the PHP client will connect to a single endpoint only, by specifying a string value for the endpoint in the ConnectionOptions, e.g.

$connectionOptions = [
    ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://127.0.0.1:8529'
];

To set up multiple servers to connect to, it is also possible to specify an array of servers instead:

$connectionOptions = [
    ConnectionOptions::OPTION_ENDPOINT    => [ 'tcp://localhost:8531', 'tcp://localhost:8532', 'tcp://localhost:8530' ]
];

Using this option requires ArangoDB 3.3 or higher and the database running in active failover mode.

The driver will by default try to connect to the first server endpoint in the endpoints array, and only try the following servers if no connection can be established. If no connection can be made to any server, the driver will throw an exception.

As it is unknown to the driver which server from the array is the current leader, the driver will connect to the specified servers in array order by default. However, to spare a few unnecessary connection attempts to failed servers, it is possible to set up caching (using Memcached) for the server list. The cached value will contain the last working server first, so that as few connection attempts as possible will need to be made.

In order to use this caching, it is required to install the Memcached module for PHP, and to set up the following relevant options in the ConnectionOptions:

$connectionOptions = [
    // memcached persistent id (will be passed to Memcached::__construct)
    ConnectionOptions::OPTION_MEMCACHED_PERSISTENT_ID => 'arangodb-php-pool',

    // memcached servers to connect to (will be passed to Memcached::addServers)
    ConnectionOptions::OPTION_MEMCACHED_SERVERS       => [ [ '127.0.0.1', 11211 ] ],

    // memcached options (will be passed to Memcached::setOptions)
    ConnectionOptions::OPTION_MEMCACHED_OPTIONS       => [ ],

    // key to store the current endpoints array under
    ConnectionOptions::OPTION_MEMCACHED_ENDPOINTS_KEY => 'arangodb-php-endpoints'

    // time-to-live for the endpoints array stored in memcached
    ConnectionOptions::OPTION_MEMCACHED_TTL           => 600
];

Creating a collection

This is just to show how a collection is created. For these examples it is not needed to create a collection prior to inserting a document, as we set ArangoConnectionOptions::OPTION_CREATE to true.

So, after we get the settings, we can start with creating a collection. We will create a collection named "users".

The below code will first set up the collection locally in a variable name $user, and then push it to the server and return the collection id created by the server:

    $collectionHandler = new ArangoCollectionHandler($connection);

    // clean up first
    if ($collectionHandler->has('users')) {
        $collectionHandler->drop('users');
    }
    if ($collectionHandler->has('example')) {
        $collectionHandler->drop('example');
    }

    // create a new collection
    $userCollection = new ArangoCollection();
    $userCollection->setName('users');
    $id = $collectionHandler->create($userCollection);

    // print the collection id created by the server
    var_dump($id);
    // check if the collection exists
    $result = $collectionHandler->has('users');
    var_dump($result);

Creating a document

After we created the collection, we can start with creating an initial document. We will create a user document in a collection named "users". This collection does not need to exist yet. The first document we'll insert in this collection will create the collection on the fly. This is because we have set OPTION_CREATE to true in $connectionOptions.

The below code will first set up the document locally in a variable name $user, and then push it to the server and return the document id created by the server:

    $handler = new ArangoDocumentHandler($connection);

    // create a new document
    $user = new ArangoDocument();

    // use set method to set document properties
    $user->set('name', 'John');
    $user->set('age', 25);
    $user->set('thisIsNull', null);

    // use magic methods to set document properties
    $user->likes = ['fishing', 'hiking', 'swimming'];

    // send the document to the server
    $id = $handler->save('users', $user);

    // check if a document exists
    $result = $handler->has('users', $id);
    var_dump($result);

    // print the document id created by the server
    var_dump($id);
    var_dump($user->getId());

Document properties can be set by using the set() method, or by directly manipulating the document properties.

As you can see, sending a document to the server is achieved by calling the save() method on the client library's DocumentHandler class. It needs the collection name ("users" in this case") plus the document object to be saved. save() will return the document id as created by the server. The id is a numeric value that might or might not fit in a PHP integer.

Adding exception handling

The above code will work but it does not check for any errors. To make it work in the face of errors, we'll wrap it into some basic exception handlers

try {
     $handler = new ArangoDocumentHandler($connection);

      // create a new document
      $user = new ArangoDocument();

      // use set method to set document properties
      $user->set('name', 'John');
      $user->set('age', 25);

      // use magic methods to set document properties
      $user->likes = ['fishing', 'hiking', 'swimming'];

      // send the document to the server
      $id = $handler->save('users', $user);

      // check if a document exists
      $result = $handler->has('users', $id);
      var_dump($result);

      // print the document id created by the server
      var_dump($id);
      var_dump($user->getId());
} catch (ArangoConnectException $e) {
  print 'Connection error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoClientException $e) {
  print 'Client error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoServerException $e) {
  print 'Server error: ' . $e->getServerCode() . ':' . $e->getServerMessage() . ' ' . $e->getMessage() . PHP_EOL;
}

Retrieving a document

To retrieve a document from the server, the get() method of the DocumentHandler class can be used. It needs the collection name plus a document id. There is also the getById() method which is an alias for get().

    // get the document back from the server
    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

/*
The result of the get() method is a Document object that you can use in an OO fashion:

object(ArangoDBClient\Document)##6 (4) {
    ["_id":"ArangoDBClient\Document":private]=>
    string(15) "2377907/4818344"
    ["_rev":"ArangoDBClient\Document":private]=>
    int(4818344)
    ["_values":"ArangoDBClient\Document":private]=>
    array(3) {
        ["age"]=>
        int(25)
        ["name"]=>
        string(4) "John"
        ["likes"]=>
        array(3) {
            [0]=>
            string(7) "fishing"
            [1]=>
            string(6) "hiking"
            [2]=>
            string(8) "swimming"
        }
    }
    ["_changed":"ArangoDBClient\Document":private]=>
    bool(false)
}
*/

Whenever the document id is yet unknown, but you want to fetch a document from the server by any of its other properties, you can use the CollectionHandler->byExample() method. It allows you to provide an example of the document that you are looking for. The example should either be a Document object with the relevant properties set, or, a PHP array with the propeties that you are looking for:

    // get a document list back from the server, using a document example
    $cursor = $collectionHandler->byExample('users', ['name' => 'John']);
    var_dump($cursor->getAll());

This will return all documents from the specified collection (here: "users") with the properties provided in the example (here: that have an attribute "name" with a value of "John"). The result is a cursor which can be iterated sequentially or completely. We have chosen to get the complete result set above by calling the cursor's getAll() method. Note that CollectionHandler->byExample() might return multiple documents if the example is ambigious.

Updating a document

To update an existing document, the update() method of the DocumentHandler class can be used. In this example we want to

set state to 'ca'

change the likes array.

    // update a document
    $userFromServer->likes = ['fishing', 'swimming'];
    $userFromServer->state = 'CA';

    $result = $handler->update($userFromServer);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

To remove an attribute using the update() method, an option has to be passed telling it to not keep attributes with null values. In this example we want to

remove the age

    // update a document removing an attribute,
    // The 'keepNull'=>false option will cause ArangoDB to
    // remove all attributes in the document,
    // that have null as their value - not only the ones defined here

    $userFromServer->likes = ['fishing', 'swimming'];
    $userFromServer->state = 'CA';
    $userFromServer->age   = null;

    $result = $handler->update($userFromServer, ['keepNull' => false]);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

To completely replace an existing document, the replace() method of the DocumentHandler class can be used. In this example we want to remove the state attribute.

    // replace a document (notice that we are using the previously fetched document)
    // In this example we are removing the state attribute
    unset($userFromServer->state);

    $result = $handler->replace($userFromServer);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

The document that is replaced using the previous example must have been fetched from the server before. If you want to update a document without having fetched it from the server before, use updateById():

    // replace a document, identified by collection and document id
    $user        = new ArangoDocument();
    $user->name  = 'John';
    $user->likes = ['Running', 'Rowing'];
    $userFromServer->state = 'CA';

    // Notice that for the example we're getting the existing
    // document id via a method call. Normally we would use the known id
    $result = $handler->replaceById('users', $userFromServer->getId(), $user);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

Deleting a document

To remove an existing document on the server, the remove() method of the DocumentHandler class will do. remove() just needs the document to be removed as a parameter:

    // remove a document on the server, using a document object
    $result = $handler->remove($userFromServer);
    var_dump($result);

Note that the document must have been fetched from the server before. If you haven't fetched the document from the server before, use the removeById() method. This requires just the collection name (here: "users") and the document id.

    // remove a document on the server, using a collection id and document id
    // In this example, we are using the id of the document we deleted in the previous example,
    // so it will throw an exception here. (we are catching it though, in order to continue)

    try {
        $result = $handler->removeById('users', $userFromServer->getId());
    } catch (\ArangoDBClient\ServerException $e) {
        $e->getMessage();
    }

Running an AQL query

To run an AQL query, use the Statement class.

The method Statement::execute creates a Cursor object which can be used to iterate over the query's result set.

    // create a statement to insert 1000 test users
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR i IN 1..1000 INSERT { _key: CONCAT("test", i) } IN users'
                   ]
    );

    // execute the statement
    $cursor = $statement->execute();

    // now run another query on the data, using bind parameters
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR u IN @@collection FILTER u.name == @name RETURN u',
                       'bindVars' => [
                           '@collection' => 'users',
                           'name' => 'John'
                       ]
                   ]
    );

    // executing the statement returns a cursor
    $cursor = $statement->execute();

    // easiest way to get all results returned by the cursor
    var_dump($cursor->getAll());

    // to get statistics for the query, use Cursor::getExtra();
    var_dump($cursor->getExtra());

Note: by default the Statement object will create a Cursor that converts each value into a Document object. This is normally the intended behavior for AQL queries that return entire documents. However, an AQL query can also return projections or any other data that cannot be converted into Document objects.

In order to suppress the conversion into Document objects, the Statement must be given the _flat attribute. This allows processing the results of arbitrary AQL queries:

    // run an AQL query that does not return documents but scalars
    // we need to set the _flat attribute of the Statement in order for this to work
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR i IN 1..1000 RETURN i',
                       '_flat' => true
                     ]
    );

    // executing the statement returns a cursor
    $cursor = $statement->execute();

    // easiest way to get all results returned by the cursor
    // note that now the results won't be converted into Document objects
    var_dump($cursor->getAll());

Exporting data

To export the contents of a collection to PHP, use the Export class. The Export class will create a light-weight cursor over all documents of the specified collection. The results can be transferred to PHP in chunks incrementally. This is the most efficient way of iterating over all documents in a collection.

   // creates an export object for collection users
    $export = new ArangoExport($connection, 'users', []);

    // execute the export. this will return a special, forward-only cursor
    $cursor = $export->execute();

    // now we can fetch the documents from the collection in blocks
    while ($docs = $cursor->getNextBatch()) {
        // do something with $docs
        var_dump($docs);
    }

    // the export can also be restricted to just a few attributes per document:
    $export = new ArangoExport(
        $connection, 'users', [
                       '_flat' => true,
                       'restrict' => [
                           'type' => 'include',
                           'fields' => ['_key', 'likes']
                       ]
                   ]
    );

    // now fetch just the configured attributes for each document
    while ($docs = $cursor->getNextBatch()) {
        // do something with $docs
        var_dump($docs);
    }

Bulk document handling

The ArangoDB-PHP driver provides a mechanism to easily fetch multiple documents from the same collection with a single request. All that needs to be provided is an array of document keys:

    $exampleCollection = new ArangoCollection();
    $exampleCollection->setName('example');
    $id = $collectionHandler->create($exampleCollection);

    // create a statement to insert 100 example documents
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR i IN 1..100 INSERT { _key: CONCAT("example", i), value: i } IN example'
                   ]
    );
    $statement->execute();

    // later on, we can assemble a list of document keys
    $keys = [];
    for ($i = 1; $i <= 100; ++$i) {
        $keys[] = 'example' . $i;
    }
    // and fetch all the documents at once
    $documents = $collectionHandler->lookupByKeys('example', $keys);
    var_dump($documents);

    // we can also bulk-remove them:
    $result = $collectionHandler->removeByKeys('example', $keys);

    var_dump($result);

Dropping a collection

To drop an existing collection on the server, use the drop() method of the CollectionHandler class. drop() just needs the name of the collection name to be dropped:

    // drop a collection on the server, using its name,
    $result = $collectionHandler->drop('users');
    var_dump($result);

    // drop the other one we created, too
    $collectionHandler->drop('example');

Custom Document class

If you want to use custom document class you can pass it's name to DocumentHandler or CollectionHandler using method setDocumentClass. Remember that Your class must extend \ArangoDBClient\Document.

$ch = new CollectionHandler($connection);
$ch->setDocumentClass('\AppBundle\Entity\Product');
$cursor = $ch->all('product');
// All returned documents will be \AppBundle\Entity\Product instances

$dh = new DocumentHandler($connection);
$dh->setDocumentClass('\AppBundle\Entity\Product');
$product = $dh->get('products', 11231234);
// Product will be \AppBundle\Entity\Product instance

See file examples/customDocumentClass.php for more details.

Logging exceptions

The driver provides a simple logging mechanism that is turned off by default. If it is turned on, the driver will log all its exceptions using PHP's standard error_log mechanism. It will call PHP's error_log() function for this. It depends on the PHP configuration if and where exceptions will be logged. Please consult your php.ini settings for further details.

To turn on exception logging in the driver, set a flag on the driver's Exception base class, from which all driver exceptions are subclassed:

use ArangoDBClient\Exception as ArangoException;

ArangoException::enableLogging();

To turn logging off, call its disableLogging method:

use ArangoDBClient\Exception as ArangoException;

ArangoException::disableLogging();

Putting it all together

Here's the full code that combines all the pieces outlined above:

// use the following line when using Composer
// require __DIR__ . '/vendor/composer/autoload.php';

// use the following line when using git
require __DIR__ . '/autoload.php';

// set up some aliases for less typing later
use ArangoDBClient\Collection as ArangoCollection;
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler;
use ArangoDBClient\Connection as ArangoConnection;
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions;
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler;
use ArangoDBClient\Document as ArangoDocument;
use ArangoDBClient\Exception as ArangoException;
use ArangoDBClient\Export as ArangoExport;
use ArangoDBClient\ConnectException as ArangoConnectException;
use ArangoDBClient\ClientException as ArangoClientException;
use ArangoDBClient\ServerException as ArangoServerException;
use ArangoDBClient\Statement as ArangoStatement;
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy;

// set up some basic connection options
$connectionOptions = [
    // database name
    ArangoConnectionOptions::OPTION_DATABASE => '_system',
    // server endpoint to connect to
    ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://127.0.0.1:8529',
    // authorization type to use (currently supported: 'Basic')
    ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
    // user for basic authorization
    ArangoConnectionOptions::OPTION_AUTH_USER => 'root',
    // password for basic authorization
    ArangoConnectionOptions::OPTION_AUTH_PASSWD => '',
    // connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
    ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive',
    // connect timeout in seconds
    ArangoConnectionOptions::OPTION_TIMEOUT => 3,
    // whether or not to reconnect when a keep-alive connection has timed out on server
    ArangoConnectionOptions::OPTION_RECONNECT => true,
    // optionally create new collections when inserting documents
    ArangoConnectionOptions::OPTION_CREATE => true,
    // optionally create new collections when inserting documents
    ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];

// turn on exception logging (logs to whatever PHP is configured)
ArangoException::enableLogging();

try {
    $connection = new ArangoConnection($connectionOptions);

    $collectionHandler = new ArangoCollectionHandler($connection);

    // clean up first
    if ($collectionHandler->has('users')) {
        $collectionHandler->drop('users');
    }
    if ($collectionHandler->has('example')) {
        $collectionHandler->drop('example');
    }

    // create a new collection
    $userCollection = new ArangoCollection();
    $userCollection->setName('users');
    $id = $collectionHandler->create($userCollection);

    // print the collection id created by the server
    var_dump($id);

    // check if the collection exists
    $result = $collectionHandler->has('users');
    var_dump($result);

    $handler = new ArangoDocumentHandler($connection);

    // create a new document
    $user = new ArangoDocument();

    // use set method to set document properties
    $user->set('name', 'John');
    $user->set('age', 25);
    $user->set('thisIsNull', null);

    // use magic methods to set document properties
    $user->likes = ['fishing', 'hiking', 'swimming'];

    // send the document to the server
    $id = $handler->save('users', $user);

    // check if a document exists
    $result = $handler->has('users', $id);
    var_dump($result);

    // print the document id created by the server
    var_dump($id);
    var_dump($user->getId());

    // get the document back from the server
    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

    // get a document list back from the server, using a document example
    $cursor = $collectionHandler->byExample('users', ['name' => 'John']);
    var_dump($cursor->getAll());

    // update a document
    $userFromServer->likes = ['fishing', 'swimming'];
    $userFromServer->state = 'CA';

    $result = $handler->update($userFromServer);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

    // update a document removing an attribute,
    // The 'keepNull'=>false option will cause ArangoDB to
    // remove all attributes in the document,
    // that have null as their value - not only the ones defined here

    $userFromServer->likes = ['fishing', 'swimming'];
    $userFromServer->state = 'CA';
    $userFromServer->age   = null;

    $result = $handler->update($userFromServer, ['keepNull' => false]);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

    // replace a document (notice that we are using the previously fetched document)
    // In this example we are removing the state attribute
    unset($userFromServer->state);

    $result = $handler->replace($userFromServer);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

    // replace a document, identified by collection and document id
    $user                  = new ArangoDocument();
    $user->name            = 'John';
    $user->likes           = ['Running', 'Rowing'];
    $userFromServer->state = 'CA';

    // Notice that for the example we're getting the existing
    // document id via a method call. Normally we would use the known id
    $result = $handler->replaceById('users', $userFromServer->getId(), $user);
    var_dump($result);

    $userFromServer = $handler->get('users', $id);
    var_dump($userFromServer);

    // remove a document on the server
    $result = $handler->remove($userFromServer);
    var_dump($result);

    // remove a document on the server, using a collection id and document id
    // In this example, we are using the id of the document we deleted in the previous example,
    // so it will throw an exception here. (we are catching it though, in order to continue)

    try {
        $result = $handler->removeById('users', $userFromServer->getId());
    } catch (\ArangoDBClient\ServerException $e) {
        $e->getMessage();
    }

    // create a statement to insert 1000 test users
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR i IN 1..1000 INSERT { _key: CONCAT("test", i) } IN users'
                   ]
    );

    // execute the statement
    $cursor = $statement->execute();

    // now run another query on the data, using bind parameters
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR u IN @@collection FILTER u.name == @name RETURN u',
                       'bindVars' => [
                           '@collection' => 'users',
                           'name' => 'John'
                       ]
                   ]
    );

    // executing the statement returns a cursor
    $cursor = $statement->execute();

    // easiest way to get all results returned by the cursor
    var_dump($cursor->getAll());

    // to get statistics for the query, use Cursor::getExtra();
    var_dump($cursor->getExtra());

    // creates an export object for collection users
    $export = new ArangoExport($connection, 'users', []);

    // execute the export. this will return a special, forward-only cursor
    $cursor = $export->execute();

    // now we can fetch the documents from the collection in blocks
    while ($docs = $cursor->getNextBatch()) {
        // do something with $docs
        var_dump($docs);
    }

    // the export can also be restricted to just a few attributes per document:
    $export = new ArangoExport(
        $connection, 'users', [
                       '_flat' => true,
                       'restrict' => [
                           'type' => 'include',
                           'fields' => ['_key', 'likes']
                       ]
                   ]
    );

    // now fetch just the configured attributes for each document
    while ($docs = $cursor->getNextBatch()) {
        // do something with $docs
        var_dump($docs);
    }

    $exampleCollection = new ArangoCollection();
    $exampleCollection->setName('example');
    $id = $collectionHandler->create($exampleCollection);

    // create a statement to insert 100 example documents
    $statement = new ArangoStatement(
        $connection, [
                       'query' => 'FOR i IN 1..100 INSERT { _key: CONCAT("example", i), value: i } IN example'
                   ]
    );
    $statement->execute();

    // later on, we can assemble a list of document keys
    $keys = [];
    for ($i = 1; $i <= 100; ++$i) {
        $keys[] = 'example' . $i;
    }
    // and fetch all the documents at once
    $documents = $collectionHandler->lookupByKeys('example', $keys);
    var_dump($documents);

    // we can also bulk-remove them:
    $result = $collectionHandler->removeByKeys('example', $keys);

    var_dump($result);

    // drop a collection on the server, using its name,
    $result = $collectionHandler->drop('users');
    var_dump($result);

    // drop the other one we created, too
    $collectionHandler->drop('example');
} catch (ArangoConnectException $e) {
    print 'Connection error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoClientException $e) {
    print 'Client error: ' . $e->getMessage() . PHP_EOL;
} catch (ArangoServerException $e) {
    print 'Server error: ' . $e->getServerCode() . ': ' . $e->getServerMessage() . ' - ' . $e->getMessage() . PHP_EOL;
}

ArangoDB Go Driver

ArangoDB GO Driver

The official ArangoDB GO Driver

Getting Started

Example Requests

Connection Management

Reference

Getting Started

ArangoDB GO Driver - Getting Started

Supported versions

ArangoDB versions 3.1 and up.

Single server & cluster setups

With or without authentication

Go 1.7 and up.

Go dependencies

None (Additional error libraries are supported).

Configuration

To use the driver, first fetch the sources into your GOPATH.

go get github.com/arangodb/go-driver

Using the driver, you always need to create a Client. The following example shows how to create a Client for a single server running on localhost.

import (
    "fmt"

    driver "github.com/arangodb/go-driver"
    "github.com/arangodb/go-driver/http"
)

...

conn, err := http.NewConnection(http.ConnectionConfig{
    Endpoints: []string{"http://localhost:8529"},
})
if err != nil {
    // Handle error
}
c, err := driver.NewClient(driver.ClientConfig{
    Connection: conn,
})
if err != nil {
    // Handle error
}

Once you have a Client you can access/create databases on the server, access/create collections, graphs, documents and so on.

The following example shows how to open an existing collection in an existing database and create a new document in that collection.

// Open "examples_books" database
db, err := c.Database(nil, "examples_books")
if err != nil {
    // Handle error
}

// Open "books" collection
col, err := db.Collection(nil, "books")
if err != nil {
    // Handle error
}

// Create document
book := Book{
    Title:   "ArangoDB Cookbook",
    NoPages: 257,
}
meta, err := col.CreateDocument(nil, book)
if err != nil {
    // Handle error
}
fmt.Printf("Created document in collection '%s' in database '%s'\n", col.Name(), db.Name())

API design

Concurrency

All functions of the driver are stricly synchronous. They operate and only return a value (or error) when they're done.

If you want to run operations concurrently, use a go routine. All objects in the driver are designed to be used from multiple concurrent go routines, except Cursor.

All database objects (except Cursor) are considered static. After their creation they won't change. E.g. after creating a Collection instance you can remove the collection, but the (Go) instance will still be there. Calling functions on such a removed collection will of course fail.

Structured error handling & wrapping

All functions of the driver that can fail return an error value. If that value is not nil, the function call is considered to be failed. In that case all other return values are set to their zero values.

All errors are structured using error checking functions named Is<SomeErrorCategory>. E.g. IsNotFound(error) return true if the given error is of the category "not found". There can be multiple internal error codes that all map onto the same category.

All errors returned from any function of the driver (either internal or exposed) wrap errors using the WithStack function. This can be used to provide detail stack trackes in case of an error. All error checking functions use the Cause function to get the cause of an error instead of the error wrapper.

Note that WithStack and Cause are actually variables to you can implement it using your own error wrapper library.

If you for example use https://github.com/pkg/errors, you want to initialize to go driver like this:

import (
    driver "github.com/arangodb/go-driver"
    "github.com/pkg/errors"
)

func init() {
    driver.WithStack = errors.WithStack
    driver.Cause = errors.Cause
}

Context aware

All functions of the driver that involve some kind of long running operation or support additional options not given as function arguments, have a context.Context argument. This enables you cancel running requests, pass timeouts/deadlines and pass additional options.

In all methods that take a context.Context argument you can pass nil as value. This is equivalent to passing context.Background().

Many functions support 1 or more optional (and infrequently used) additional options. These can be used with a With<OptionName> function. E.g. to force a create document call to wait until the data is synchronized to disk, use a prepared context like this:

ctx := driver.WithWaitForSync(parentContext)
collection.CreateDocument(ctx, yourDocument)

Example Requests

ArangoDB GO Driver - Example requests

Connecting to ArangoDB

conn, err := http.NewConnection(http.ConnectionConfig{
    Endpoints: []string{"http://localhost:8529"},
    TLSConfig: &tls.Config{ /*...*/ },
})
if err != nil {
    // Handle error
}
c, err := driver.NewClient(driver.ClientConfig{
    Connection: conn,
    Authentication: driver.BasicAuthentication("user", "password"),
})
if err != nil {
    // Handle error
}

Opening a database

ctx := context.Background()
db, err := client.Database(ctx, "myDB")
if err != nil {
    // handle error
}

Opening a collection

ctx := context.Background()
col, err := db.Collection(ctx, "myCollection")
if err != nil {
    // handle error
}

Checking if a collection exists

ctx := context.Background()
found, err := db.CollectionExists(ctx, "myCollection")
if err != nil {
    // handle error
}

Creating a collection

ctx := context.Background()
options := &driver.CreateCollectionOptions{ /* ... */ }
col, err := db.CreateCollection(ctx, "myCollection", options)
if err != nil {
    // handle error
}

Reading a document from a collection

var doc MyDocument
ctx := context.Background()
meta, err := col.ReadDocument(ctx, myDocumentKey, &doc)
if err != nil {
    // handle error
}

Reading a document from a collection with an explicit revision

var doc MyDocument
revCtx := driver.WithRevision(ctx, "mySpecificRevision")
meta, err := col.ReadDocument(revCtx, myDocumentKey, &doc)
if err != nil {
    // handle error
}

Creating a document

doc := MyDocument{
    Name: "jan",
    Counter: 23,
}
ctx := context.Background()
meta, err := col.CreateDocument(ctx, doc)
if err != nil {
    // handle error
}
fmt.Printf("Created document with key '%s', revision '%s'\n", meta.Key, meta.Rev)

Removing a document

ctx := context.Background()
err := col.RemoveDocument(revCtx, myDocumentKey)
if err != nil {
    // handle error
}

Removing a document with an explicit revision

revCtx := driver.WithRevision(ctx, "mySpecificRevision")
err := col.RemoveDocument(revCtx, myDocumentKey)
if err != nil {
    // handle error
}

Updating a document

ctx := context.Background()
patch := map[string]interface{}{
    "Name": "Frank",
}
meta, err := col.UpdateDocument(ctx, myDocumentKey, patch)
if err != nil {
    // handle error
}

Querying documents, one document at a time

ctx := context.Background()
query := "FOR d IN myCollection LIMIT 10 RETURN d"
cursor, err := db.Query(ctx, query, nil)
if err != nil {
    // handle error
}
defer cursor.Close()
for {
    var doc MyDocument
    meta, err := cursor.ReadDocument(ctx, &doc)
    if driver.IsNoMoreDocuments(err) {
        break
    } else if err != nil {
        // handle other errors
    }
    fmt.Printf("Got doc with key '%s' from query\n", meta.Key)
}

Querying documents, fetching total count

ctx := driver.WithQueryCount(context.Background())
query := "FOR d IN myCollection RETURN d"
cursor, err := db.Query(ctx, query, nil)
if err != nil {
    // handle error
}
defer cursor.Close()
fmt.Printf("Query yields %d documents\n", cursor.Count())

Querying documents, with bind variables

ctx := context.Background()
query := "FOR d IN myCollection FILTER d.Name == @name RETURN d"
bindVars := map[string]interface{}{
    "name": "Some name",
}
cursor, err := db.Query(ctx, query, bindVars)
if err != nil {
    // handle error
}
defer cursor.Close()
...

Connection Management

ArangoDB GO Driver - Connection Management

Failover

The driver supports multiple endpoints to connect to. All request are in principle send to the same endpoint until that endpoint fails to respond. In that case a new endpoint is chosen and the operation is retried.

The following example shows how to connect to a cluster of 3 servers.

conn, err := http.NewConnection(http.ConnectionConfig{
    Endpoints: []string{"http://server1:8529", "http://server2:8529", "http://server3:8529"},
})
if err != nil {
    // Handle error
}
c, err := driver.NewClient(driver.ClientConfig{
    Connection: conn,
})
if err != nil {
    // Handle error
}

Note that a valid endpoint is an URL to either a standalone server, or a URL to a coordinator in a cluster.

Failover: Exact behavior

The driver monitors the request being send to a specific server (endpoint). As soon as the request has been completely written, failover will no longer happen. The reason for that is that several operations cannot be (safely) retried. E.g. when a request to create a document has been send to a server and a timeout occurs, the driver has no way of knowing if the server did or did not create the document in the database.

If the driver detects that a request has been completely written, but still gets an error (other than an error response from Arango itself), it will wrap the error in a ResponseError. The client can test for such an error using IsResponseError.

If a client received a ResponseError, it can do one of the following:

Retry the operation and be prepared for some kind of duplicate record / unique constraint violation.

Perform a test operation to see if the "failed" operation did succeed after all.

Simply consider the operation failed. This is risky, since it can still be the case that the operation did succeed.

Failover: Timeouts

To control the timeout of any function in the driver, you must pass it a context configured with context.WithTimeout (or context.WithDeadline).

In the case of multiple endpoints, the actual timeout used for requests will be shorter than the timeout given in the context. The driver will divide the timeout by the number of endpoints with a maximum of 3. This ensures that the driver can try up to 3 different endpoints (in case of failover) without being canceled due to the timeout given by the client. E.g.

With 1 endpoint and a given timeout of 1 minute, the actual request timeout will be 1 minute.

With 3 endpoints and a given timeout of 1 minute, the actual request timeout will be 20 seconds.

With 8 endpoints and a given timeout of 1 minute, the actual request timeout will be 20 seconds.

For most requests you want a actual request timeout of at least 30 seconds.

Secure connections (SSL)

The driver supports endpoints that use SSL using the https URL scheme.

The following example shows how to connect to a server that has a secure endpoint using a self-signed certificate.

conn, err := http.NewConnection(http.ConnectionConfig{
    Endpoints: []string{"https://localhost:8529"},
    TLSConfig: &tls.Config{InsecureSkipVerify: true},
})
if err != nil {
    // Handle error
}
c, err := driver.NewClient(driver.ClientConfig{
    Connection: conn,
})
if err != nil {
    // Handle error
}

Spring Data ArangoDB

Spring Data ArangoDB

Getting Started

Reference

Migration

Learn more

ArangoDB

Demo

JavaDoc 1.0.0

JavaDoc 2.0.0

Changelog

Getting Started

Spring Data ArangoDB - Getting Started

Supported versions

Spring Data ArangoDB | Spring Data | ArangoDB
1.3.x | 1.13.x | 3.0*, 3.1+
2.3.x | 2.0.x | 3.0*, 3.1+
3.0.x | 2.0.x | 3.0*, 3.1+

Spring Data ArangoDB requires ArangoDB 3.0 or higher - which you can download here - and Java 8 or higher.

Note: ArangoDB 3.0 does not support the default transport protocol VelocyStream. A manual switch to HTTP is required. See chapter configuration. Also ArangoDB 3.0 does not support geospatial queries.

Maven

To use Spring Data ArangoDB in your project, your build automation tool needs to be configured to include and use the Spring Data ArangoDB dependency. Example with Maven:

<dependency>
  <groupId>com.arangodb</groupId>
  <artifactId>arangodb-spring-data</artifactId>
  <version>2.3.1</version>
</dependency>

There is a demonstration app, which contains common use cases and examples of how to use Spring Data ArangoDB's functionality.

Configuration

You can use Java to configure your Spring Data environment as show below. Setting up the underlying driver (ArangoDB.Builder) with default configuration automatically loads a properties file arangodb.properties, if it exists in the classpath.

@Configuration
@EnableArangoRepositories(basePackages = { "com.company.mypackage" })
public class MyConfiguration extends AbstractArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder();
  }

  @Override
  public String database() {
    // Name of the database to be used
    return "example-database";
  }

}

The driver is configured with some default values:

property-key | description | default value
arangodb.host | ArangoDB host | 127.0.0.1
arangodb.port | ArangoDB port | 8529
arangodb.timeout | socket connect timeout(millisecond) | 0
arangodb.user | Basic Authentication User
arangodb.password | Basic Authentication Password
arangodb.useSsl | use SSL connection | false

To customize the configuration, the parameters can be changed in the Java code.

@Override
public ArangoDB.Builder arango() {
  ArangoDB.Builder arango = new ArangoDB.Builder()
    .host("127.0.0.1")
    .port(8529)
    .user("root");
  return arango;
}

In addition you can use the arangodb.properties or a custom properties file to supply credentials to the driver.

Properties file

arangodb.hosts=127.0.0.1:8529
arangodb.user=root
arangodb.password=

Custom properties file

@Override
public ArangoDB.Builder arango() {
  InputStream in = MyClass.class.getResourceAsStream("my.properties");
  ArangoDB.Builder arango = new ArangoDB.Builder()
    .loadProperties(in);
  return arango;
}

Note: When using ArangoDB 3.0 it is required to set the transport protocol to HTTP and fetch the dependency org.apache.httpcomponents:httpclient.

@Override
public ArangoDB.Builder arango() {
  ArangoDB.Builder arango = new ArangoDB.Builder()
    .useProtocol(Protocol.HTTP_JSON);
  return arango;
}

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.1</version>
</dependency>

Reference

Spring Data ArangoDB - Reference

Template

Queries

Document Manipulation

Multiple Document Manipulation

Collection Manipulation

Repositories

Queries

Derived queries

Query methods

Named queries

Document Manipulation

Multiple Document Manipulation

Query by example

Mapping

Document

Edge

Reference

Relations

Indexes

Converter

Events

Template

Template

With ArangoTemplate Spring Data ArangoDB offers a central support for interactions with the database over a rich feature set. It mostly offers the features from the ArangoDB Java driver with additional exception translation from the drivers exceptions to the Spring Data access exceptions inheriting the DataAccessException class. The ArangoTemplate class is the default implementation of the operations interface ArangoOperations which developers of Spring Data are encouraged to code against.

Queries

ArangoOperations.query

ArangoOperations.query(String query, Map<String, Object> bindVars, AqlQueryOptions options, Class<T> entityClass) : ArangoCursor<T>

Performs a database query using the given query and bindVars, then returns a new ArangoCursor instance for the result list.

Arguments

query: String

An AQL query string

bindVars: Map<String, Object>

key/value pairs defining the variables to bind the query to

options: AqlQueryOptions

count: Boolean

Indicates whether the number of documents in the result set should be returned in the "count" attribute of the result. Calculating the "count" attribute might have a performance impact for some queries in the future so this option is turned off by default, and "count" is only returned when requested.

ttl: Integer

The time-to-live for the cursor (in seconds). The cursor will be removed on the server automatically after the specified amount of time. This is useful to ensure garbage collection of cursors that are not fully fetched by clients. If not set, a server-defined value will be used.

batchSize: Integer

Maximum number of result documents to be transferred from the server to the client in one roundtrip. If this attribute is not set, a server-controlled default value will be used. A batchSize value of 0 is disallowed.

memoryLimit: Long

The maximum number of memory (measured in bytes) that the query is allowed to use. If set, then the query will fail with error "resource limit exceeded" in case it allocates too much memory. A value of 0 indicates that there is no memory limit.

cache: Boolean

Flag to determine whether the AQL query cache shall be used. If set to false, then any query cache lookup will be skipped for the query. If set to true, it will lead to the query cache being checked for the query if the query cache mode is either on or demand.

failOnWarning: Boolean

When set to true, the query will throw an exception and abort instead of producing a warning. This option should be used during development to catch potential issues early. When the attribute is set to false, warnings will not be propagated to exceptions and will be returned with the query result. There is also a server configuration option --query.fail-on-warning for setting the default value for failOnWarning so it does not need to be set on a per-query level.

profile: Boolean

If set to true, then the additional query profiling information will be returned in the sub-attribute profile of the extra return attribute if the query result is not served from the query cache.

maxTransactionSize: Long

Transaction size limit in bytes. Honored by the RocksDB storage engine only.

maxWarningCount: Long

Limits the maximum number of warnings a query will return. The number of warnings a query will return is limited to 10 by default, but that number can be increased or decreased by setting this attribute.

intermediateCommitCount: Long

Maximum number of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

intermediateCommitSize: Long

Maximum total size of operations after which an intermediate commit is performed automatically. Honored by the RocksDB storage engine only.

satelliteSyncWait: Double

This enterprise parameter allows to configure how long a DBServer will have time to bring the satellite collections involved in the query into sync. The default value is 60.0 (seconds). When the max time has been reached the query will be stopped.

skipInaccessibleCollections

AQL queries (especially graph traversals) will treat collection to which a user has no access rights as if these collections were empty. Instead of returning a forbidden access error, your queries will execute normally. This is intended to help with certain use-cases: A graph contains several collections and different users execute AQL queries on that graph. You can now naturally limit the accessible results by changing the access rights of users on collections. This feature is only available in the Enterprise Edition.

fullCount: Boolean

If set to true and the query contains a LIMIT clause, then the result will have an extra attribute with the sub-attributes stats and fullCount, { ... , "extra": { "stats": { "fullCount": 123 } } }. The fullCount attribute will contain the number of documents in the result before the last top-level LIMIT in the query was applied. It can be used to count the number of documents that match certain filter criteria, but only return a subset of them, in one go. It is thus similar to MySQL's SQL_CALC_FOUND_ROWS hint. Note that setting the option will disable a few LIMIT optimizations and may lead to more documents being processed, and thus make queries run longer. Note that the fullCount attribute may only be present in the result if the query has a top-level LIMIT clause and the LIMIT clause is actually used in the query.

maxPlans: Integer

Limits the maximum number of plans that are created by the AQL query optimizer.

rules: Collection<String>

A list of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling the optimizer to include or exclude specific rules. To disable a rule, prefix its name with a -, to enable a rule, prefix it with a +. There is also a pseudo-rule all, which will match all optimizer rules.

stream: Boolean

Specify true and the query will be executed in a streaming fashion. The query result is not stored on the server, but calculated on the fly. Beware: long-running queries will need to hold the collection locks for as long as the query cursor exists. When set to false a query will be executed right away in its entirety. In that case query results are either returned right away (if the resultset is small enough), or stored on the arangod instance and accessible via the cursor API (with respect to the ttl). It is advisable to only use this option on short-running queries or without exclusive locks (write-locks on MMFiles). Please note that the query options cache, count and fullCount will not work on streaming queries. Additionally query statistics, warnings and profiling data will only be available after the query is finished. The default value is false.

type: Class<T>

The type of the result (POJO class, VPackSlice or Collection/List/Map)

Examples

@Autowired ArangoOperations template;

ArangoCursor<MyObject> cursor = template.query("FOR i IN @@collection RETURN i"
                                               new MapBuilder().put("@collection", MyObject.class).get(),
                                               new AqlQueryOptions(),
                                               MyObject.class);

Document Manipulation

Manipulating documents

ArangoOperations.exists

ArangoOperations.exists(String id, Class<?> entityClass) : boolean

Checks whether the document exists by reading a single document head

Arguments

id: String

The id or key of the document

entityClass: Class<T>

The entity class which represents the collection

Examples

@Autowired ArangoOperations template;

boolean exists = template.exists("some-id", MyObject.class);

ArangoOperations.find

ArangoOperations.find(String id, Class<T> entityClass, DocumentReadOptions options) : Optional<T>

Retrieves the document with the given id from a collection.

Arguments

id: String

The id or key of the document

entityClass: Class<T>

The entity class which represents the collection

options: DocumentReadOptions

ifNoneMatch: String

Document revision must not contain If-None-Match

ifMatch: String

Document revision must contain If-Match

catchException: Boolean

Whether or not catch possible thrown exceptions

Examples

@Autowired ArangoOperations template;

Optional<MyObject> doc = template.find("some-id", MyObject.class, new DocumentReadOptions());

ArangoOperations.repsert

ArangoOperations.repsert(T value) : void

Creates a new document from the given document, unless there is already a document with the id given. In that case it replaces the document.

Arguments

value: T

A representation of a single document

Examples

@Autowired ArangoOperations template;

MyObject myObj = ...
template.repsert(myObj);

ArangoOperations.insert

ArangoOperations.insert(T value, DocumentCreateOptions options) : DocumentEntity

Creates a new document from the given document, unless there is already a document with the _key given. If no _key is given, a new unique _key is generated automatically.

Arguments

value: T

A representation of a single document

options: DocumentCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

overwrite: Boolean

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject myObj = ...
DocumentEntity info = template.insert(myObj, new DocumentCreateOptions());

ArangoOperations.replace

ArangoOperations.replace(String id, T value, DocumentReplaceOptions options) : DocumentEntity

Replaces the document with id with the one in the body, provided there is such a document and no precondition is violated.

Arguments

id: String

The id or key of the document

value: T

A representation of a single document

options: DocumentReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject myObj = ...
DocumentEntity info = template.replace("some-id", myObj, new DocumentReplaceOptions());

ArangoOperations.update

ArangoOperations.update(String id, T value, DocumentUpdateOptions options) : DocumentEntity

Partially updates the document identified by document id or key. The value must contain a document with the attributes to patch (the patch document). All attributes from the patch document will be added to the existing document if they do not yet exist, and overwritten in the existing document if they do exist there.

Arguments

id: String

The id or key of the document

value: T

A representation of a single document

options: DocumentUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject myObj = ...
DocumentEntity info = template.update("some-id", myObj, new DocumentReplaceOptions());

ArangoOperations.delete

ArangoOperations.delete(String id, Class<?> entityClass, DocumentDeleteOptions options) : DocumentEntity

Deletes the document with the given id from a collection.

Arguments

id: String

The id or key of the document

entityClass: Class<T>

The entity class which represents the collection

options: DocumentDeleteOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Replace a document based on target revision

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

template.delete("some-id", MyObject.class, new DocumentDeleteOptions());

Multiple Document Manipulation

Manipulating multiple documents

ArangoOperations.find

ArangoOperations.find(Iterable<String> ids, Class<T> entityClass) : Iterable<T>

Retrieves multiple documents with the given ids from a collection.

Arguments

ids: Iterable<String>

The ids or keys of the documents

entityClass: Class<T>

The entity type of the documents

Examples

@Autowired ArangoOperations template;

Iterable<MyObject> docs = template.find(Arrays.asList("some-id", "some-other-id"), MyObject.class);

ArangoOperations.findAll

ArangoOperations.findAll(Class<T> entityClass) : Iterable<T>

Retrieves all documents from a collection.

Arguments

entityClass: Class<T>

The entity class which represents the collection

Examples

@Autowired ArangoOperations template;

Iterable<MyObject> docs = template.find(MyObject.class);

ArangoOperations.insert

ArangoOperations.insert(Iterable<T> values, Class<T> entityClass, DocumentCreateOptions options) : MultiDocumentEntity

Creates new documents from the given documents, unless there is already a document with the _key given. If no _key is given, a new unique _key is generated automatically.

Arguments

values: Iterable<T>

A List of documents

entityClass: Class<T>

The entity class which represents the collection

options: DocumentCreateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

overwrite: Boolean

If set to true, the insert becomes a replace-insert. If a document with the same _key already exists the new document is not rejected with unique constraint violated but will replace the old document.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject obj1 = ...
MyObject obj2 = ...
MyObject obj3 = ...
template.insert(Arrays.asList(obj1, obj2, obj3));

ArangoOperations.replace

ArangoOperations.replace(Iterable<T> values, Class<T> entityClass, DocumentReplaceOptions options) : MultiDocumentEntity

Replaces multiple documents in the specified collection with the ones in the values, the replaced documents are specified by the _key attributes in the documents in values.

Arguments

values: Iterable<T>

A List of documents

entityClass: Class<T>

The entity class which represents the collection

options: DocumentReplaceOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject obj1 = ...
MyObject obj2 = ...
MyObject obj3 = ...
template.replace(Arrays.asList(obj1, obj2, obj3), new DocumentReplaceOptions());

ArangoOperations.update

ArangoOperations.update(Iterable<T> values, Class<T> entityClass, DocumentUpdateOptions options) : MultiDocumentEntity

Partially updates documents, the documents to update are specified by the _key attributes in the objects on values. Vales must contain a list of document updates with the attributes to patch (the patch documents). All attributes from the patch documents will be added to the existing documents if they do not yet exist, and overwritten in the existing documents if they do exist there.

Arguments

values: Iterable<T>

A List of documents

entityClass: Class<T>

The entity class which represents the collection

options: DocumentUpdateOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ignoreRevs: Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch: String

Replace a document based on target revision

returnNew: Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

MyObject obj1 = ...
MyObject obj2 = ...
MyObject obj3 = ...
template.update(Arrays.asList(obj1, obj2, obj3), new DocumentUpdateOptions());

ArangoOperations.delete

ArangoOperations.delete(Iterable<Object> values, Class<?> entityClass, DocumentDeleteOptions options) : MultiDocumentEntity

Deletes multiple documents from a collection.

Arguments

values: Iterable<Object>

The keys of the documents or the documents themselves

entityClass: Class<?>

The entity class which represents the collection

options: DocumentDeleteOptions

waitForSync: Boolean

Wait until document has been synced to disk.

ifMatch: String

Replace a document based on target revision

returnOld: Boolean

Additionally return the complete old document under the attribute old in the result. Only available if the overwrite option is used.

silent: Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

Examples

@Autowired ArangoOperations template;

collection.delete(Arrays.asList("some-id", "some-other-id"), MyObject.class, new DocumentDeleteOptions());

Collection Manipulation

Manipulating the collection

ArangoOperations.collection

ArangoOperations.collection(Class<?> entityClass) : CollectionOperations

ArangoOperations.collection(String name) : CollectionOperations

Returns the operations interface for a collection. If the collection does not exists, it is created automatically.

Arguments

entityClass: Class<?>

The entity type representing the collection

name: String

The name of the collection

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);

// -- or --

CollectionOperations collection = template.collection("some-collection-name");

CollectionOperations.truncate

CollectionOperations.truncate() : void

Removes all documents from the collection, but leaves the indexes intact

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
collection.truncate();

CollectionOperations.drop

CollectionOperations.drop() : void

Deletes the collection from the database.

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
collection.drop();

CollectionOperations.count

CollectionOperation.count() : long

Counts the documents in a collection

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
long count = collection.count();

CollectionOperations.getProperties

CollectionOperations.getProperties() : CollectionPropertiesEntity

Reads the properties of the specified collection

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
CollectionPropertiesEntity properties = collection.getProperties();

CollectionOperation.getIndexes

CollectionOperations.getIndexes() : Collection<IndexEntity>

Returns all indexes of the collection

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
Collection<IndexEntity> indexes = collection.getIndexes();

CollectionOperations.ensureHashIndex

CollectionOperations.ensureHashIndex(Iterable<String> fields, HashIndexOptions options) : IndexEntity

Creates a hash index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: HashIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

deduplicate: Boolean

If false, the deduplication of array values is turned off.

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
IndexEntity index = collection.ensureHashIndex(Arrays.asList("a", "b.c"), new HashIndexOptions());
// the index has been created with the handle `index.getId()`

CollectionOperations.ensureSkiplistIndex

CollectionOperations.ensureSkiplistIndex(Iterable<String> fields, SkiplistIndexOptions options) : IndexEntity

Creates a skip-list index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: SkiplistIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

deduplicate: Boolean

If false, the deduplication of array values is turned off.

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
IndexEntity index = collection.ensureSkiplistIndex(Arrays.asList("a", "b.c"), new SkiplistIndexOptions());
// the index has been created with the handle `index.getId()`

CollectionOperations.ensureGeoIndex

CollectionOperations.ensureGeoIndex(Iterable<String> fields, GeoIndexOptions options) : IndexEntity

Creates a geo index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: GeoIndexOptions

geoJson: Boolean

If a geo-spatial index on a location is constructed and geoJson is true, then the order within the array is longitude followed by latitude. This corresponds to the format described in.

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
IndexEntity index = collection.ensureGeoIndex(Arrays.asList("latitude", "longitude"), new GeoIndexOptions());
// the index has been created with the handle `index.getId()`

CollectionOperations.ensureFulltextIndex

CollectionOperations.ensureFulltextIndex(Iterable<String> fields, FulltextIndexOptions options) : IndexEntity

Creates a fulltext index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: FulltextIndexOptions

minLength: Integer

Minimum character length of words to index. Will default to a server-defined value if unspecified. It is thus recommended to set this value explicitly when creating the index.

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
IndexEntity index = collection.ensureFulltextIndex(Arrays.asList("description"), new FulltextIndexOptions());
// the index has been created with the handle `index.getId()`

CollectionOperations.ensurePersistentIndex

CollectionOperations.ensurePersistentIndex(Iterable<String> fields, PersistentIndexOptions options) : IndexEntity

Creates a persistent index for the collection if it does not already exist.

Arguments

fields: Iterable<String>

A list of attribute paths

options: PersistentIndexOptions

unique: Boolean

If true, then create a unique index

sparse: Boolean

If true, then create a sparse index

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
IndexEntity index = collection.ensurePersistentIndex(Arrays.asList("a", "b.c"), new PersistentIndexOptions());
// the index has been created with the handle `index.getId()`

CollectionOperations.dropIndex

CollectionOperations.dropIndex(String id) : void

Deletes the index with the given id from the collection.

Arguments

id: String

The index-handle

Examples

@Autowired ArangoOperations template;

CollectionOperations collection = template.collection(MyObject.class);
collection.dropIndex("some-index");

Repositories

Repositories

Spring Data Commons provides a composable repository infrastructure which Spring Data ArangoDB is built on. These allow for interface-based composition of repositories consisting of provided default implementations for certain interfaces (like CrudRepository) and custom implementations for other methods.

The base interface of Spring Data ArangoDB is ArangoRepository. It extends the Spring Data interfaces PagingAndSortingRepository and QueryByExampleExecutor. To get access to all Sping Data ArangoDB repository functionallity simply create your own interface extending ArangoRepository<T, ID>.

The type T represents your domain class and type ID the type of your field annotated with @Id in your domain class. This field is persistend in ArangoDB as document field _key.

Examples

@Document
public class MyDomainClass {
  @Id
  private String id;

}

public interface MyRepository extends ArangoRepository<MyDomainClass, String> {

}

Instances of a Repository are created in Spring beans through the auto-wired mechanism of Spring.

public class MySpringBean {

  @Autowired
  private MyRepository rep;

}

Queries

Queries

Spring Data ArangoDB supports three kinds of queries:

Derived queries

Query methods

Named queries

Return types

The method return type for single results can be a primitive type, a domain class, Map<String, Object>, BaseDocument, BaseEdgeDocument, Optional<Type>, GeoResult<Type>.

The method return type for multiple results can additionally be ArangoCursor<Type>, Iterable<Type>, Collection<Type>, List<Type>, Set<Type>, Page<Type>, Slice<Type>, GeoPage<Type>, GeoResults<Type> where Type can be everything a single result can be.

AQL query options

You can set additional options for the query and the created cursor over the class AqlQueryOptions which you can simply define as a method parameter without a specific name. AqlQuery options can also be defined with the @QueryOptions annotation, as shown below. Aql query options from an annotation and those from an argument are merged if both exist, with those in the argument taking precedence.

The AqlQueryOptions allows you to set the cursor time-to-live, batch-size, caching flag and several other settings. This special parameter works with both query methods and derived queries. Keep in mind that some options, like time-to-live, are only effective if the method return type isArangoCursor<T> or Iterable<T>.

Examples

public interface MyRepository extends Repository<Customer, String> {

  @Query("FOR c IN #collection FILTER c.name == @0 RETURN c")
  Iterable<Customer> query(String name, AqlQueryOptions options);

  Iterable<Customer> findByName(String name, AqlQueryOptions options);

  @QueryOptions(maxPlans = 1000, ttl = 128)
  ArangoCursor<Customer> findByAddressZipCode(ZipCode zipCode);

  @Query("FOR c IN #collection FILTER c[@field] == @value RETURN c")
  @QueryOptions(cache = true, ttl = 128)
  ArangoCursor<Customer> query(Map<String, Object> bindVars, AqlQueryOptions options);

}

Paging and sorting

Spring Data ArangoDB supports Spring Data's Pageable and Sort parameters for repository query methods. If these parameters are used together with a native query, either through @Query annotation or named queries, a placeholder must be specified:

#pageable for Pageable parameter

#sort for Sort parameter

Sort properties or paths are attributes separated by dots (e.g. customer.age). Some rules apply for them:

they must not begin or end with a dot (e.g. .customer.age)

dots in attributes are supported, but the whole attribute must be enclosed by backticks (e.g. customer.`attr.with.dots`

backticks in attributes are supported, but they must be escaped with a backslash (e.g. customer.attr_with\` )

any backslashes (that do not escape a backtick) are escaped (e.g. customer\ => customer\\)

Examples

just.`some`.`attributes.that`.`form\``.a path\`.\  is converted to
`just`.`some`.`attributes.that`.`form\``.`a path\``.`\\`

Native queries example

public interface CustomerRepository extends ArangoRepository<Customer> {

  @Query("FOR c IN #collection FILTER c.name == @1 #pageable RETURN c")
  Page<Customer> findByNameNative(Pageable pageable, String name);

  @Query("FOR c IN #collection FILTER c.name == @1 #sort RETURN c")
  List<Customer> findByNameNative(Sort sort, String name);
}

// don't forget to specify the var name of the document
final Pageable page = PageRequest.of(1, 10, Sort.by("c.age"));
repository.findByNameNative(page, "Matt");

final Sort sort = Sort.by(Direction.DESC, "c.age");
repository.findByNameNative(sort, "Tony");

Derived queries example

public interface CustomerRepository extends ArangoRepository<Customer> {

  Page<Customer> findByName(Pageable pageable, String name);

  List<Customer> findByName(Sort sort, String name);
}

// no var name is necessary for derived queries
final Pageable page = PageRequest.of(1, 10, Sort.by("age"));
repository.findByName(page, "Matt");

final Sort sort = Sort.by(Direction.DESC, "age");
repository.findByName(sort, "Tony");

Derived queries

Derived queries

Semantic parts

Spring Data ArangoDB supports queries derived from methods names by splitting it into its semantic parts and converting into AQL. The mechanism strips the prefixes find..By, get..By, query..By, read..By, stream..By, count..By, exists..By, delete..By, remove..By from the method and parses the rest. The By acts as a separator to indicate the start of the criteria for the query to be built. You can define conditions on entity properties and concatenate them with And and Or.

The complete list of part types for derived methods is below, where doc is a document in the database

Keyword | Sample | Predicate
IsGreaterThan, GreaterThan, After | findByAgeGreaterThan(int age) | doc.age > age
IsGreaterThanEqual, GreaterThanEqual | findByAgeIsGreaterThanEqual(int age) | doc.age >= age
IsLessThan, LessThan, Before | findByAgeIsLessThan(int age) | doc.age < age
IsLessThanEqualLessThanEqual | findByAgeLessThanEqual(int age) | doc.age <= age
IsBetween, Between | findByAgeBetween(int lower, int upper) | lower < doc.age < upper
IsNotNull, NotNull | findByNameNotNull() | doc.name != null
IsNull, Null | findByNameNull() | doc.name == null
IsLike, Like | findByNameLike(String name) | doc.name LIKE name
IsNotLike, NotLike | findByNameNotLike(String name) | NOT(doc.name LIKE name)
IsStartingWith, StartingWith, StartsWith | findByNameStartsWith(String prefix) | doc.name LIKE prefix
IsEndingWith, EndingWith, EndsWith | findByNameEndingWith(String suffix) | doc.name LIKE suffix
Regex, MatchesRegex, Matches | findByNameRegex(String pattern) | REGEX_TEST(doc.name, name, ignoreCase)
(No Keyword) | findByFirstName(String name) | doc.name == name
IsTrue, True | findByActiveTrue() | doc.active == true
IsFalse, False | findByActiveFalse() | doc.active == false
Is, Equals | findByAgeEquals(int age) | doc.age == age
IsNot, Not | findByAgeNot(int age) | doc.age != age
IsIn, In | findByNameIn(String[] names) | doc.name IN names
IsNotIn, NotIn | findByNameIsNotIn(String[] names) | doc.name NOT IN names
IsContaining, Containing, Contains | findByFriendsContaining(String name) | name IN doc.friends
IsNotContaining, NotContaining, NotContains | findByFriendsNotContains(String name) | name NOT IN doc.friends
Exists | findByFriendNameExists() | HAS(doc.friend, name)

Examples

public interface MyRepository extends ArangoRepository<Customer, String> {

  // FOR c IN customers FILTER c.name == @0 RETURN c
  ArangoCursor<Customer> findByName(String name);
  ArangoCursor<Customer> getByName(String name);

  // FOR c IN customers
  // FILTER c.name == @0 && c.age == @1
  // RETURN c
  ArangoCursor<Customer> findByNameAndAge(String name, int age);

  // FOR c IN customers
  // FILTER c.name == @0 || c.age == @1
  // RETURN c
  ArangoCursor<Customer> findByNameOrAge(String name, int age);
}

You can apply sorting for one or multiple sort criteria by appending OrderBy to the method and Asc or Desc for the directions.

public interface MyRepository extends ArangoRepository<Customer, String> {

  // FOR c IN customers
  // FILTER c.name == @0
  // SORT c.age DESC RETURN c
  ArangoCursor<Customer> getByNameOrderByAgeDesc(String name);

  // FOR c IN customers
  // FILTER c.name = @0
  // SORT c.name ASC, c.age DESC RETURN c
  ArangoCursor<Customer> findByNameOrderByNameAscAgeDesc(String name);

}

Property expression

Property expressions can refer only to direct and nested properties of the managed domain class. The algorithm checks the domain class for the entire expression as the property. If the check fails, the algorithm splits up the expression at the camel case parts from the right and tries to find the corresponding property.

Examples

@Document("customers")
public class Customer {
  private Address address;
}

public class Address {
  private ZipCode zipCode;
}

public interface MyRepository extends ArangoRepository<Customer, String> {

  // 1. step: search domain class for a property "addressZipCode"
  // 2. step: search domain class for "addressZip.code"
  // 3. step: search domain class for "address.zipCode"
  ArangoCursor<Customer> findByAddressZipCode(ZipCode zipCode);
}

It is possible for the algorithm to select the wrong property if the domain class also has a property which matches the first split of the expression. To resolve this ambiguity you can use _ as a separator inside your method-name to define traversal points.

Examples

@Document("customers")
public class Customer {
  private Address address;
  private AddressZip addressZip;
}

public class Address {
  private ZipCode zipCode;
}

public class AddressZip {
  private String code;
}

public interface MyRepository extends ArangoRepository<Customer, String> {

  // 1. step: search domain class for a property "addressZipCode"
  // 2. step: search domain class for "addressZip.code"
  // creates query with "x.addressZip.code"
  ArangoCursor<Customer> findByAddressZipCode(ZipCode zipCode);

  // 1. step: search domain class for a property "addressZipCode"
  // 2. step: search domain class for "addressZip.code"
  // 3. step: search domain class for "address.zipCode"
  // creates query with "x.address.zipCode"
  ArangoCursor<Customer> findByAddress_ZipCode(ZipCode zipCode);

}

Geospatial queries

Geospatial queries are a subsection of derived queries. To use a geospatial query on a collection, a geo index must exist on that collection. A geo index can be created on a field which is a two element array, corresponding to latitude and longitude coordinates.

As a subsection of derived queries, geospatial queries support all the same return types, but also support the three return types GeoPage, GeoResult and Georesults. These types must be used in order to get the distance of each document as generated by the query.

There are two kinds of geospatial query, Near and Within. Near sorts documents by distance from the given point, while within both sorts and filters documents, returning those within the given distance range or shape.

Examples

public interface MyRepository extends ArangoRepository<City, String> {

    GeoResult<City> getByLocationNear(Point point);

    GeoResults<City> findByLocationWithinOrLocationWithin(Box box, Polygon polygon);

    //Equivalent queries
    GeoResults<City> findByLocationWithinOrLocationWithin(Point point, int distance);
    GeoResults<City> findByLocationWithinOrLocationWithin(Point point, Distance distance);
    GeoResults<City> findByLocationWithinOrLocationWithin(Circle circle);

}

Query methods

Query methods

Queries using ArangoDB Query Language (AQL) can be supplied with the @Query annotation on methods.

Passing collection name

Instead of writing the collection name statically into the query string, the placeholder #collection can be specified.

public interface MyRepository extends ArangoRepository<Customer, String>{

  // FOR c IN customer RETURN c
  @Query("FOR c IN #collection RETURN c")
  ArangoCursor<Customer> query();

}

Passing bind parameters

There are three ways of passing bind parameters to the query in the query annotation.

Number matching

Using number matching, arguments will be substituted into the query in the order they are passed to the query method.

public interface MyRepository extends ArangoRepository<Customer, String>{

  @Query("FOR c IN #collection FILTER c.name == @0 AND c.surname == @1 RETURN c")
  ArangoCursor<Customer> query(String name, String surname);

}

@Param

With the @Param annotation, the argument will be placed in the query at the place corresponding to the value passed to the @Param annotation.

public interface MyRepository extends ArangoRepository<Customer, String>{

  @Query("FOR c IN #collection FILTER c.name == @name AND c.surname == @surname RETURN c")
  ArangoCursor<Customer> query(@Param("name") String name, @Param("surname") String surname);

}

@BindVars

In addition you can use a method parameter of type Map<String, Object> annotated with @BindVars as your bind parameters. You can then fill the map with any parameter used in the query. (see here for more Information about Bind Parameters).

public interface MyRepository extends ArangoRepository<Customer, String>{

  @Query("FOR c IN #collection FILTER c.name == @name AND c.surname = @surname RETURN c")
  ArangoCursor<Customer> query(@BindVars Map<String, Object> bindVars);

}

A mixture of any of these methods can be used. Parameters with the same name from an @Param annotation will override those in the bindVars.

public interface MyRepository extends ArangoRepository<Customer, String>{

  @Query("FOR c IN #collection FILTER c.name == @name AND c.surname = @surname RETURN c")
  ArangoCursor<Customer> query(@BindVars Map<String, Object> bindVars, @Param("name") String name);

}

Query options

AqlQueryOptions can also be passed to the driver, as an argument anywhere in the method signature.

public interface MyRepository extends ArangoRepository<Customer, String>{

  @Query("FOR c IN #collection FILTER c.name == @name AND c.surname == @surname RETURN c")
  ArangoCursor<Customer> query(@Param("name") String name, @Param("surname") String surname, AqlQueryOptions options);

}

Named queries

Named queries

An alternative to using the @Query annotation on methods is specifying them in a separate .properties file. The default path for the file is META-INF/arango-named-queries.properties and can be changed with the EnableArangoRepositories#namedQueriesLocation() setting. The entries in the properties file must adhere to the following convention: {simple entity name}.{method name} = {query}. Let's assume we have the following repository interface:

package com.arangodb.repository;

public interface CustomerRepository extends ArangoRepository<Customer, String> {

    Customer findByUsername(@Param("username") String username);

}

The corresponding arango-named-queries.properties file looks like this:

Customer.findByUsername = FOR c IN customers FILTER c.username == @username RETURN c

The queries specified in the properties file are no different than the queries that can be defined with the @Query annotation. The only difference is that the queries are in one place. If there is a @Query annotation present and a named query defined, the query in the @Query annotation takes precedence.

Document Manipulation

Manipulating documents

ArangoRepository.existsById

ArangoRepository.existsById(ID id) : boolean

Returns whether an entity with the given id exists.

Arguments

id: ID

The id (_key) of the document. Must not be null.

Examples

@Autowired MyRepository repository;

boolean exists = repository.existsById("some-id");

ArangoRepository.findById

ArangoRepository.findById(ID id) : Optional<T>

Retrieves an entity by its id.

Arguments

id: ID

The id (_key) of the document. Must not be null.

Examples

@Autowired MyRepository repository;

Optional<MyDomainClass> entity = repository.findById("some-id");

ArangoRepository.save

ArangoRepository.save(S entity) : S

Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

Arguments

entity: S

The entity to save in the database. Must not be null.

@Autowired MyRepository repository;

MyDomainClass entity = new MyDomainClass();
entity = repository.save(entity);

ArangoRepository.deleteById

ArangoRepository.deleteById(ID id) : void

Deletes the entity with the given id.

Arguments

id: ID

The id (_key) of the document. Must not be null.

Examples

@Autowired MyRepository repository;

repository.deleteById("some-id");

ArangoRepository.delete

ArangoRepository.delete(T entity) : void

Deletes a given entity.

Arguments

entity: T

The entity to delete. Must not be null.

Examples

@Autowired MyRepository repository;

MyDomainClass entity = ...
repository.delete(entity);

Multiple Document Manipulation

Manipulating multiple documents

ArangoRepository.findAll

ArangoRepository.findAll() : Iterable<T>

Returns all instances of the type.

Examples

@Autowired MyRepository repository;

Iterable<MyDomainClass> entities = repository.findAll();

ArangoRepository.findAllById

ArangoRepository.findAllById(Iterable<ID> ids) : Iterable<T>

Returns all instances of the type with the given IDs.

Arguments

ids: Iterable<ID>

The ids (_keys) of the documents

Examples

@Autowired MyRepository repository;

Iterable<MyDomainClass> entities = repository.findAllById(Arrays.asList("some-id", "some-other-id"));

ArangoRepository.saveAll

ArangoRepository.saveAll(Iterable<S> entities) : Iterable<S>

Saves all given entities.

Arguments

entities: Iterable<S>

A list of entities to save.

Examples

@Autowired MyRepository repository;

MyDomainClass obj1 = ...
MyDomainClass obj2 = ...
MyDomainClass obj3 = ...
repository.saveAll(Arrays.asList(obj1, obj2, obj3))

ArangoRepository.deleteAll (method 1)

ArangoRepository.deleteAll() : void

Deletes all entities managed by the repository.

Examples

@Autowired MyRepository repository;

repository.deleteAll();

ArangoRepository.deleteAll (method 2)

ArangoRepository.deleteAll(Iterable<? extends T> entities) : void

Deletes the given entities.

Arguments

entities: Iterable<? extends T>

The entities to delete.

Examples

@Autowired MyRepository repository;

MyDomainClass obj1 = ...
MyDomainClass obj2 = ...
MyDomainClass obj3 = ...
repository.deleteAll(Arrays.asList(obj1, obj2, obj3))

Query by example

Query by example

ArangoRepository.exists

ArangoRepository.exists(Example<S> example) : boolean

Checks whether the data store contains elements that match the given Example.

Arguments

example: Example<S>

The example to use. Must not be null.

Examples

@Autowired MyRepository repository;

MyDomainClass sample = new MyDomainClass();
sample.setName("John"); // set some data in sample
boolean exists = repository.exists(Example.of(sample));

ArangoRepository.findOne

ArangoRepository.findOne(Example<S> example) : Optional<S>

Returns a single entity matching the given Example or Optional#empty() if none was found.

Arguments

example: Example<S>

The example to use. Must not be null.

Examples

@Autowired MyRepository repository;

MyDomainClass sample = new MyDomainClass();
sample.setName("John"); // set some data in sample
MyDomainClass entity = repository.findOne(Example.of(sample));

ArangoRepository.findAll

ArangoRepository.findAll(Example<S> example) : Iterable<S>

Returns all entities matching the given Example. In case no match could be found an empty Iterable is returned.

Arguments

example: Example<S>

The example to use. Must not be null.

Examples

@Autowired MyRepository repository;

MyDomainClass sample = new MyDomainClass();
sample.setName("John"); // set some data in sample
Iterable<MyDomainClass> entities = repository.findAll(Example.of(sample));

ArangoRepository.count

ArangoRepository.count(Example<S> example) : long

Returns the number of instances matching the given Example.

Arguments

example: Example<S>

The example to use. Must not be null.

Examples

@Autowired MyRepository repository;

MyDomainClass sample = new MyDomainClass();
sample.setName("John"); // set some data in sample
long count = repository.count(Example.of(sample));

Mapping

Mapping

In this section we will describe the features and conventions for mapping Java objects to documents and how to override those conventions with annotation based mapping metadata.

Conventions

The Java class name is mapped to the collection name

The non-static fields of a Java object are used as fields in the stored document

The Java field name is mapped to the stored document field name

All nested Java object are stored as nested objects in the stored document

The Java class needs a constructor which meets the following criteria:

in case of a single constructor:

a non-parameterized constructor or

a parameterized constructor

in case of multiple constructors:

a non-parameterized constructor or

a parameterized constructor annotated with @PersistenceConstructor

Type conventions

ArangoDB uses VelocyPack as it's internal storage format which supports a large number of data types. In addition Spring Data ArangoDB offers - with the underlying Java driver - built-in converters to add additional types to the mapping.

Java type | VelocyPack type
java.lang.String | string
java.lang.Boolean | bool
java.lang.Integer | signed int 4 bytes, smallint
java.lang.Long | signed int 8 bytes, smallint
java.lang.Short | signed int 2 bytes, smallint
java.lang.Double | double
java.lang.Float | double
java.math.BigInteger | string
java.math.BigDecimal | string
java.lang.Number | double
java.lang.Character | string
java.util.UUID | string
java.lang.byte[] | string (Base64)
java.util.Date | string (date-format ISO 8601)
java.sql.Date | string (date-format ISO 8601)
java.sql.Timestamp | string (date-format ISO 8601)
java.time.Instant | string (date-format ISO 8601)
java.time.LocalDate | string (date-format ISO 8601)
java.time.LocalDateTime | string (date-format ISO 8601)
java.time.OffsetDateTime | string (date-format ISO 8601)
java.time.ZonedDateTime | string (date-format ISO 8601)

Type mapping

As collections in ArangoDB can contain documents of various types, a mechanism to retrieve the correct Java class is required. The type information of properties declared in a class may not be enough to restore the original class (due to inheritance). If the declared complex type and the actual type do not match, information about the actual type is stored together with the document. This is necessary to restore the correct type when reading from the DB. Consider the following example:

public class Person {
    private String name;
    private Address homeAddress;
    // ...

    // getters and setters omitted
}

public class Employee extends Person {
    private Address workAddress;
    // ...

    // getters and setters omitted
}

public class Address {
    private final String street;
    private final String number;
    // ...

    public Address(String street, String number) {
        this.street = street;
        this.number = number;
    }

    // getters omitted
}

@Document
public class Company {
    @Key
    private String key;
    private Person manager;

    // getters and setters omitted
}

Employee manager = new Employee();
manager.setName("Jane Roberts");
manager.setHomeAddress(new Address("Park Avenue", "432/64"));
manager.setWorkAddress(new Address("Main Street",  "223"));
Company comp = new Company();
comp.setManager(manager);

The serialized document for the DB looks like this:

{
  "manager": {
    "name": "Jane Roberts",
    "homeAddress": {
      "street": "Park Avenue",
      "number": "432/64"
    },
    "workAddress": {
      "street": "Main Street",
      "number": "223"
    },
    "_class": "com.arangodb.Employee"
  },
  "_class": "com.arangodb.Company"
}

Type hints are written for top-level documents (as a collection can contain different document types) as well as for every value if it's a complex type and a sub-type of the property type declared. Maps and Collections are excluded from type mapping. Without the additional information about the concrete classes used, the document couldn't be restored in Java. The type information of the manager property is not enough to determine the Employee type. The homeAddress and workAddress properties have the same actual and defined type, thus no type hint is needed.

Customizing type mapping

By default, the fully qualified class name is stored in the documents as a type hint. A custom type hint can be set with the @TypeAlias("my-alias") annotation on an entity. Make sure that it is an unique identifier across all entities. If we would add a TypeAlias("employee") annotation to the Employee class above, it would be persisted as "_class": "employee".

The default type key is _class and can be changed by overriding the typeKey() method of the AbstractArangoConfiguration class.

If you need to further customize the type mapping process, the arangoTypeMapper() method of the configuration class can be overridden. The included DefaultArangoTypeMapper can be customized by providing a list of TypeInformationMappers that create aliases from types and vice versa.

In order to fully customize the type mapping process you can provide a custom type mapper implementation by extending the DefaultArangoTypeMapper class.

Deactivating type mapping

To deactivate the type mapping process, you can return null from the typeKey() method of the AbstractArangoConfiguration class. No type hints are stored in the documents with this setting. If you make sure that each defined type corresponds to the actual type, you can disable the type mapping, otherwise it can lead to exceptions when reading the entities from the DB.

Annotations

Annotation overview

annotation | level | description
@Document | class | marks this class as a candidate for mapping
@Edge | class | marks this class as a candidate for mapping
@Id | field | stores the field as the system field _key
@Rev | field | stores the field as the system field _rev
@Field("alt-name") | field | stores the field with an alternative name
@Ref | field | stores the _id of the referenced document and not the nested document
@From | field | stores the _id of the referenced document as the system field _from
@To | field | stores the _id of the referenced document as the system field _to
@Relations | field | vertices which are connected over edges
@Transient | field, method, annotation | marks a field to be transient for the mapping framework, thus the property will not be persisted and not further inspected by the mapping framework
@PersistenceConstructor | constructor | marks a given constructor - even a package protected one - to use when instantiating the object from the database
@TypeAlias("alias") | class | set a type alias for the class when persisted to the DB
@HashIndex | class | describes a hash index
@HashIndexed | field | describes how to index the field
@SkiplistIndex | class | describes a skiplist index
@SkiplistIndexed | field | describes how to index the field
@PersistentIndex | class | describes a persistent index
@PersistentIndexed | field | describes how to index the field
@GeoIndex | class | describes a geo index
@GeoIndexed | field | describes how to index the field
@FulltextIndex | class | describes a fulltext index
@FulltextIndexed | field | describes how to index the field
@CreatedBy | field | Declares a field as the one representing the principal that created the entity containing the field.
@CreatedDate | field | Declares a field as the one representing the date the entity containing the field was created.
@LastModifiedBy | field | Declares a field as the one representing the principal that recently modified the entity containing the field.
@LastModifiedDate | field | Declares a field as the one representing the date the entity containing the field was recently modified.

Document

Document

Annotation @Document

The annotations @Document applied to a class marks this class as a candidate for mapping to the database. The most relevant parameter is value to specify the collection name in the database. The annotation @Document specifies the collection type to DOCUMENT.

@Document(value="persons")
public class Person {
  ...
}

Spring Expression support

Spring Data ArangoDB supports the use of SpEL expressions within @Document#value. This feature lets you define a dynamic collection name which can be used to implement multi tenancy applications.

@Component
public class TenantProvider {

    public String getId() {
        // threadlocal lookup
    }

}

@Document("#{tenantProvider.getId()}_persons")
public class Person {
  ...
}

Annotation @From and @To

With the annotations @From and @To applied on a collection or array field in a class annotated with @Document the nested edge objects are fetched from the database. Each of the nested edge objects has to be stored as separate edge document in the edge collection described in the @Edge annotation of the nested object class with the _id of the parent document as field _from or _to.

@Document("persons")
public class Person {
  @From
  private List<Relation> relations;
}

@Edge(name="relations")
public class Relation {
  ...
}

The database representation of Person in collection persons looks as follow:

{
  "_key" : "123",
  "_id" : "persons/123"
}

and the representation of Relation in collection relations:

{
  "_key" : "456",
  "_id" : "relations/456",
  "_from" : "persons/123"
  "_to" : ".../..."
}
{
  "_key" : "789",
  "_id" : "relations/456",
  "_from" : "persons/123"
  "_to" : ".../..."
}
...

Note: Since arangodb-spring-data 3.0.0 the annotations @From and @To also work on non-collection/non-array fields. If multiple edges are linked with the entity, it is not guaranteed that the same edge is returned every time. Use at your own risk.

Edge

Edge

Annotation @Edge

The annotations @Edge applied to a class marks this class as a candidate for mapping to the database. The most relevant parameter is value to specify the collection name in the database. The annotation @Edge specifies the collection type to EDGE.

@Edge("relations")
public class Relation {
  ...
}

Spring Expression support

Spring Data ArangoDB supports the use of SpEL expressions within @Edge#value. This feature lets you define a dynamic collection name which can be used to implement multi tenancy applications.

@Component
public class TenantProvider {

    public String getId() {
        // threadlocal lookup
    }

}

@Edge("#{tenantProvider.getId()}_relations")
public class Relation {
  ...
}

Annotation @From and @To

With the annotations @From and @To applied on a field in a class annotated with @Edge the nested object is fetched from the database. The nested object has to be stored as a separate document in the collection described in the @Document annotation of the nested object class. The _id field of this nested object is stored in the fields _from or _to within the edge document.

@Edge("relations")
public class Relation {
  @From
  private Person c1;
  @To
  private Person c2;
}

@Document(value="persons")
public class Person {
  @Id
  private String id;
}

The database representation of Relation in collection relations looks as follow:

{
  "_key" : "123",
  "_id" : "relations/123",
  "_from" : "persons/456",
  "_to" : "persons/789"
}

and the representation of Person in collection persons:

{
  "_key" : "456",
  "_id" : "persons/456",
}
{
  "_key" : "789",
  "_id" : "persons/789",
}

Note: If you want to save an instance of Relation, both Person objects (from & to) already have to be persisted and the class Person needs a field with the annotation @Id so it can hold the persisted _id from the database.

Reference

Reference

With the annotation @Ref applied on a field the nested object isn’t stored as a nested object in the document. The _id field of the nested object is stored in the document and the nested object has to be stored as a separate document in another collection described in the @Document annotation of the nested object class. To successfully persist an instance of your object the referencing field has to be null or it's instance has to provide a field with the annotation @Id including a valid id.

Examples

@Document(value="persons")
public class Person {
  @Ref
  private Address address;
}

@Document("addresses")
public class Address {
  @Id
  private String id;
  private String country;
  private String street;
}

The database representation of Person in collection persons looks as follow:

{
  "_key" : "123",
  "_id" : "persons/123",
  "address" : "addresses/456"
}

and the representation of Address in collection addresses:

{
  "_key" : "456",
  "_id" : "addresses/456",
  "country" : "...",
  "street" : "..."
}

Without the annotation @Ref at the field address, the stored document would look:

{
  "_key" : "123",
  "_id" : "persons/123",
  "address" : {
    "country" : "...",
     "street" : "..."
  }
}

Relations

Relations

With the annotation @Relations applied on a collection or array field in a class annotated with @Document the nested objects are fetched from the database over a graph traversal with your current object as the starting point. The most relevant parameter is edge. With edge you define the edge collection - which should be used in the traversal - using the class type. With the parameter depth you can define the maximal depth for the traversal (default 1) and the parameter direction defines whether the traversal should follow outgoing or incoming edges (default Direction.ANY).

Examples

@Document(value="persons")
public class Person {
  @Relations(edge=Relation.class, depth=1, direction=Direction.ANY)
  private List<Person> friends;
}

@Edge(name="relations")
public class Relation {

}

Note: Since arangodb-spring-data 3.0.0 the annotation @Relations also work on non-collection/non-array fields. If multiple documents are linked with the entity, it is not guaranteed that the same document is returned every time. Use at your own risk.

Indexes

Indexes

Annotation @\Indexed

With the @<IndexType>Indexed annotations user defined indexes can be created at a collection level by annotating single fields of a class.

Possible @<IndexType>Indexed annotations are:

@HashIndexed

@SkiplistIndexed

@PersistentIndexed

@GeoIndexed

@FulltextIndexed

The following example creates a hash index on the field name and a separate hash index on the field age:

public class Person {
  @HashIndexed
  private String name;

  @HashIndexed
  private int age;
}

With the @<IndexType>Indexed annotations different indexes can be created on the same field.

The following example creates a hash index and also a skiplist index on the field name:

public class Person {
  @HashIndexed
  @SkiplistIndexed
  private String name;
}

Annotation @\Index

If the index should include multiple fields the @<IndexType>Index annotations can be used on the type instead.

Possible @<IndexType>Index annotations are:

@HashIndex

@SkiplistIndex

@PersistentIndex

@GeoIndex

@FulltextIndex

The following example creates a single hash index on the fields name and age, note that if a field is renamed in the database with @Field, the new field name must be used in the index declaration:

@HashIndex(fields = {"fullname", "age"})
public class Person {
  @Field("fullname")
  private String name;

  private int age;
}

The @<IndexType>Index annotations can also be used to create an index on a nested field.

The following example creates a single hash index on the fields name and address.country:

@HashIndex(fields = {"name", "address.country"})
public class Person {
  private String name;

  private Address address;
}

The @<IndexType>Index annotations and the @<IndexType>Indexed annotations can be used at the same time in one class.

The following example creates a hash index on the fields name and age and a separate hash index on the field age:

@HashIndex(fields = {"name", "age"})
public class Person {
  private String name;

  @HashIndexed
  private int age;
}

The @<IndexType>Index annotations can be used multiple times to create more than one index in this way.

The following example creates a hash index on the fields name and age and a separate hash index on the fields name and gender:

@HashIndex(fields = {"name", "age"})
@HashIndex(fields = {"name", "gender"})
public class Person {
  private String name;

  private int age;

  private Gender gender
}

Converter

Converter

Registering a Spring Converter

The AbstractArangoConfiguration provides a convenient way to register Spring Converter by overriding the method customConverters().

Examples

@Configuration
public class MyConfiguration extends AbstractArangoConfiguration {

  @Override
  protected Collection<Converter<?, ?>> customConverters() {
    Collection<Converter<?, ?>> converters = new ArrayList<>();
    converters.add(new MyConverter());
    return converters;
  }

}

Implementing a Spring Converter

A Converter is used for reading if the source type is of type VPackSlice or DBDocumentEntity.

A Converter is used for writing if the target type is of type VPackSlice, DBDocumentEntity, BigInteger, BigDecimal, java.sql.Date, java.sql.Timestamp, Instant, LocalDate, LocalDateTime, OffsetDateTime, ZonedDateTime, Boolean, Short, Integer, Byte, Float, Double, Character, String, Date, Class, Enum, boolean[], long[], short[], int[], byte[], float[], double[] or char[].

Examples

public class MyConverter implements Converter<MyObject, VPackSlice> {

  @Override
  public VPackSlice convert(final MyObject source) {
    VPackBuilder builder = new VPackBuilder();
    // map fields of MyObject to builder
    return builder.slice();
  }

}

For performance reasons VPackSlice should always be used within a converter. If your object is too complexe, you can also use DBDocumentEntity to simplify the mapping.

Events

Events

Spring Data ArangoDB includes several ApplicationEvent events that your application can respond to by registering subclasses of AbstractArangoEventListener in the ApplicationContext.

The following callback methods are present in AbstractArangoEventListener:

onAfterLoad: Called in ArangoTemplate#find and ArangoTemplate#query after the object is loaded from the database.

onBeforeSave: Called in ArangoTemplate#insert/#update/#replace before the object is converted and send to the database.

onAfterSave: Called in ArangoTemplate#insert/#update/#replace after the object is send to the database.

onBeforeDelete: Called in ArangoTemplate#delete before the object is converted and send to the database.

onAfterDelete: Called in ArangoTemplate#delete after the object is deleted from the database.

Examples

package my.mapping.events;

public class BeforePersonSavedListener extends AbstractArangoEventListener<Person> {

  @Override
  public void onBeforeSave(BeforeSaveEvent<Person> event) {
    // do some logging or data manipulation
  }

}

To register the listener add @ComponentScan with the package of your listener to your configuration class.

@Configuration
@ComponentScan("my.mapping.events")
public class MyConfiguration extends AbstractArangoConfiguration {
  ...

Migration

Spring Data ArangoDB - Migration

Migrating 1.x to 3.0

Migrating 2.x to 3.0

Migrating 1.x to 3.0

Migrating Spring Data ArangoDB 2.x to 3.0

see Migrating 2.x to 3.0

Migrating 2.x to 3.0

Migrating Spring Data ArangoDB 2.x to 3.0

Annotations @Key

The annotation @Key is removed. Use @Id instead.

Annotations @Id

The annotation @Id is now saved in the database as field _key instead of _id. All operations in ArangoOperations and ArangoRepository still work with @Id and also now supports non-String fields.

If you - for some reason - need the value of _id within your application, you can use the annotation @ArangoId on a String field instead of @Id.

Note: The field annotated with @ArangoId will not be persisted in the database. It only exists for reading purposes.

ArangoRepository

ArangoRepository now requires a second generic type. This type ID represents the type of your domain object field annotated with @Id.

Examples

public class Customer {
  @Id private String id;
}

public interface CustomerRepository extends ArangoRepository<Customer, String> {

}

Annotation @Param

The annotation com.arangodb.springframework.annotation.Param is removed. Use org.springframework.data.repository.query.Param instead.

DBEntity

DBEntity is removed. Use VPackSlice in your converter instead.

DBCollectionEntity

DBCollectionEntity is removed. Use VPackSlice in your converter instead.

ArangoDB Spark Connector

ArangoDB Spark Connector

Getting Started

Reference

Changelog

Getting Started

ArangoDB Spark Connector - Getting Started

Maven

<dependencies>
  <dependency>
    <groupId>com.arangodb</groupId>
    <artifactId>arangodb-spark-connector</artifactId>
    <version>1.0.2</version>
  </dependency>
    ....
</dependencies>

SBT

libraryDependencies += "com.arangodb" % "arangodb-spark-connector" % "1.0.2"

Configuration

property-key | description | default value
arangodb.hosts | comma separated list of ArangoDB hosts | 127.0.0.1:8529
arangodb.user | basic authentication user | root
arangodb.password | basic authentication password |
arangodb.useSsl | use SSL connection | false
arangodb.ssl.keyStoreFile | SSL certificate keystore file |
arangodb.ssl.passPhrase | SSL pass phrase |
arangodb.ssl.protocol | SSL protocol | TLS

Setup SparkContext

Scala

val conf = new SparkConf()
    .set("arangodb.hosts", "127.0.0.1:8529")
    .set("arangodb.user", "myUser")
    .set("arangodb.password", "myPassword")
    ...

val sc = new SparkContext(conf)

Java

SparkConf conf = new SparkConf()
    .set("arangodb.hosts", "127.0.0.1:8529")
    .set("arangodb.user", "myUser")
    .set("arangodb.password", "myPassword");
    ...

JavaSparkContext sc = new JavaSparkContext(conf);

Reference

ArangoDB Spark Connector - Reference

Scala

Java

Java

ArangoDB Spark Connector - Java Reference

ArangoSpark.save

ArangoSpark.save[T](rdd: JavaRDD[T], collection: String, options: WriteOptions)

Save data from rdd into ArangoDB

Arguments

rdd: JavaRDD[T]

The rdd with the data to save

collection: String

The collection to save in

options: WriteOptions

database: String

Database to write into

hosts: String

Alternative hosts to context property arangodb.hosts

user: String

Alternative user to context property arangodb.user

password: String

Alternative password to context property arangodb.password

useSsl: Boolean

Alternative useSsl to context property arangodb.useSsl

sslKeyStoreFile: String

Alternative sslKeyStoreFile to context property arangodb.ssl.keyStoreFile

sslPassPhrase: String

Alternative sslPassPhrase to context property arangodb.ssl.passPhrase

sslProtocol: String

Alternative sslProtocol to context property arangodb.ssl.protocol

Examples

JavaSparkContext sc = ...
List<MyBean> docs = ...
JavaRDD<MyBean> documents = sc.parallelize(docs);
ArangoSpark.save(documents, "myCollection", new WriteOptions().database("myDB"));

ArangoSpark.load

ArangoSparkload[T](sparkContext: JavaSparkContext, collection: String, options: ReadOptions, clazz: Class[T]): ArangoJavaRDD[T]

Load data from ArangoDB into rdd

Arguments

sparkContext: JavaSparkContext

The sparkContext containing the ArangoDB configuration

collection: String

The collection to load data from

options: ReadOptions

database: String

Database to write into

hosts: String

Alternative hosts to context property arangodb.hosts

user: String

Alternative user to context property arangodb.user

password: String

Alternative password to context property arangodb.password

useSsl: Boolean

Alternative useSsl to context property arangodb.useSsl

sslKeyStoreFile: String

Alternative sslKeyStoreFile to context property arangodb.ssl.keyStoreFile

sslPassPhrase: String

Alternative sslPassPhrase to context property arangodb.ssl.passPhrase

sslProtocol: String

Alternative sslProtocol to context property arangodb.ssl.protocol

clazz: Class[T]

The type of the document

Examples

JavaSparkContext sc = ...
ArangoJavaRDD<MyBean> rdd = ArangoSpark.load(sc, "myCollection", new ReadOptions().database("myDB"), MyBean.class);

ArangoRDD.filter

ArangoJavaRDD.filter(condition: String): ArangoJavaRDD[T]

Adds a filter condition. If used multiple times, the conditions will be combined with a logical AND.

Arguments

condition: String

The condition for the filter statement. Use doc inside to reference the document. e.g. "doc.name == 'John'"

Examples

JavaSparkContext sc = ...
ArangoJavaRDD<MyBean> rdd = ArangoSpark.load(sc, "myCollection", new ReadOptions().database("myDB"), MyBean.class);
ArangoJavaRDD<MyBean> rddFiltered = rdd.filter("doc.test <= 50");

Scala

ArangoDB Spark Connector - Scala Reference

ArangoSpark.save

ArangoSpark.save[T](rdd: RDD[T], collection: String, options: WriteOptions)

ArangoSpark.save[T](dataset: Dataset[T], collection: String, options: WriteOptions)

Save data from rdd or dataset into ArangoDB

Arguments

rdd/dataset: RDD[T] or Dataset[T]

The rdd or dataset with the data to save

collection: String

The collection to save in

options: WriteOptions

database: String

Database to write into

hosts: String

Alternative hosts to context property arangodb.hosts

user: String

Alternative user to context property arangodb.user

password: String

Alternative password to context property arangodb.password

useSsl: Boolean

Alternative useSsl to context property arangodb.useSsl

sslKeyStoreFile: String

Alternative sslKeyStoreFile to context property arangodb.ssl.keyStoreFile

sslPassPhrase: String

Alternative sslPassPhrase to context property arangodb.ssl.passPhrase

sslProtocol: String

Alternative sslProtocol to context property arangodb.ssl.protocol

Examples

val sc: SparkContext = ...
val documents = sc.parallelize((1 to 100).map { i => MyBean(i) })
ArangoSpark.save(documents, "myCollection", WriteOptions("myDB"))

ArangoSpark.saveDF

ArangoSpark.saveDF(dataframe: DataFrame, collection: String, options: WriteOptions)

Save data from dataframe into ArangoDB

Arguments

dataframe: DataFrame`

The dataFrame with the data to save

collection: String

The collection to save in

options: WriteOptions

database: String

Database to write into

hosts: String

Alternative hosts to context property arangodb.hosts

user: String

Alternative user to context property arangodb.user

password: String

Alternative password to context property arangodb.password

useSsl: Boolean

Alternative useSsl to context property arangodb.useSsl

sslKeyStoreFile: String

Alternative sslKeyStoreFile to context property arangodb.ssl.keyStoreFile

sslPassPhrase: String

Alternative sslPassPhrase to context property arangodb.ssl.passPhrase

sslProtocol: String

Alternative sslProtocol to context property arangodb.ssl.protocol

Examples

val sc: SparkContext = ...
val documents = sc.parallelize((1 to 100).map { i => MyBean(i) })
val sql: SQLContext = SQLContext.getOrCreate(sc);
val df = sql.createDataFrame(documents, classOf[MyBean])
ArangoSpark.saveDF(df, "myCollection", WriteOptions("myDB"))

ArangoSpark.load

ArangoSpark.load[T: ClassTag](sparkContext: SparkContext, collection: String, options: ReadOptions): ArangoRDD[T]

Load data from ArangoDB into rdd

Arguments

sparkContext: SparkContext

The sparkContext containing the ArangoDB configuration

collection: String

The collection to load data from

options: ReadOptions

database: String

Database to write into

hosts: String

Alternative hosts to context property arangodb.hosts

user: String

Alternative user to context property arangodb.user

password: String

Alternative password to context property arangodb.password

useSsl: Boolean

Alternative useSsl to context property arangodb.useSsl

sslKeyStoreFile: String

Alternative sslKeyStoreFile to context property arangodb.ssl.keyStoreFile

sslPassPhrase: String

Alternative sslPassPhrase to context property arangodb.ssl.passPhrase

sslProtocol: String

Alternative sslProtocol to context property arangodb.ssl.protocol

Examples

val sc: SparkContext = ...
val rdd = ArangoSpark.load[MyBean](sc, "myCollection", ReadOptions("myDB"))

ArangoRDD.filter

ArangoRDD.filter(condition: String): ArangoRDD[T]

Adds a filter condition. If used multiple times, the conditions will be combined with a logical AND.

Arguments

condition: String

The condition for the filter statement. Use doc inside to reference the document. e.g. "doc.name == 'John'"

Examples

val sc: SparkContext = ...
val rdd = ArangoSpark.load[MyBean](sc, "myCollection").filter("doc.name == 'John'")