Arangodb官网:https://www.arangodb.com/
GitHub开源代码:https://github.com/arangodb/arangodb-java-driver
Maven依赖配置:
<dependencies>
<dependency>
<groupId>com.arangodb</groupId>
<artifactId>arangodb-java-driver</artifactId>
<version>4.2.2</version>
</dependency>
</dependencies>
建立连接
ArangoDB arangoDB = new ArangoDB.Builder()
.host("127.0.0.1", 8529)
.user("myuser")
.password("mypassword")
.useProtocol(Protocol.VST)
.build();
Database操作
创建数据库:
arangoDB.createDatabase("myDatabase");
删除数据库:
arangoDB.db("myDatabase").drop();
Collection操作
创建集合:
arangoDB.db("myDatabase").createCollection("myCollection", null);
清空集合数据:
arangoDB.db("myDatabase").collection("myCollection").truncate();
删除集合:
arangoDB.db("myDatabase").collection("myCollection").drop();
Document操作
支持三种类型的数据作为Arangodb中的文档: Java POJO、VelocyPack、Json字符串,下面以Java POJO为例
定义文档Java POJO对象:
public class User {
private String _key;
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User() {
}
/*
* + getter and setter
*/
}
插入单条文档:
User user = new User("zhangsan", 20);
user.set_key("001");
arangoDB.db("myDatabase").collection("myCollection").insertDocument(user);
注:也可以不设置_key值,则系统会自动生成一个key
批量插入文档:
Collection<User> documents = new ArrayList<User>();
User user1 = new User("zhangSan", 20);
User user2 = new User("liSi", 21);
User user3 = new User("wangWu", 22);
documents.add(user1);
documents.add(user2);
documents.add(user3);
arangoDB.db("myDatabase").collection("myCollection").insertDocuments(documents);
修改文档:
User user = new User("zhangsan1", 201);
user.set_key("001");
arangoDB.db("myDatabase").collection("myCollection").updateDocument(user.get_key(),user);
修改和替换的区别:
修改:只会修改提供的字段,替换:会将提供的字段替换原有的整个文档,假设原有文档内容为:
`{
"age": 20,
"name": "zhangsan"
}`
修改:
arangoDB.db("myDatabase").collection("myCollection").updateDocument(user.get_key(),"{\"weight\":130}");
结果新增了一个字段:
`{
"age": 20,
"name": "zhangsan",
"weight": 130
}`
替换:
arangoDB.db("myDatabase").collection("myCollection").replaceDocument(user.get_key(),"{\"weight\":130}");
结果原有文档中的所有内容被替换成一个字段:
`{
"weight": 130
}`
删除文档:
arangoDB.db("myDatabase").collection("myCollection").deleteDocument(user.get_key());
文档读取:
读取成json字符串:
String json = arangoDB.db("myDatabase").collection("myCollection").getDocument("001", String.class);
读取成Java POJO对象:
User user = arangoDB.db("myDatabase").collection("myCollection").getDocument("001", User.class);
使用_id读取:
String json = arangoDB.db("myDatabase").getDocument("myCollection/001", String.class);