快速问题:在ArangoDB中,如果我创建一个唯一索引(例如一个唯一的哈希索引),ArangoDB是否会验证该属性的唯一性,或者只是假设它,因为我告诉它它是唯一的?我很好奇我是否应该在创建唯一索引之前通过验证步骤来验证数据的唯一性。
答案 0 :(得分:3)
如您所知,ArangoDB会在您使用它们之前构建索引。 如果它无法确保唯一性,它将抛出异常:
127.0.0.1:8529@_system> c = db._create("c")
[ArangoCollection 169, "c" (type document, status loaded)]
127.0.0.1:8529@_system> c.insert({"abc":1})
{
"_id" : "c/172",
"_key" : "172",
"_rev" : "_T1m73_m---"
}
127.0.0.1:8529@_system> c.insert({"abc":1})
{
"_id" : "c/176",
"_key" : "176",
"_rev" : "_T1m748K---"
}
127.0.0.1:8529@_system> c.ensureIndex(
...> {"type":"hash","unique":true,"fields":["abc"]})
JavaScript exception in file '.../arangosh.js' at 97,7:
ArangoError 1210: unique constraint violated
! throw error;
! ^
stacktrace: ArangoError: unique constraint violated
at Object.exports.checkRequestResult (.../arangosh.js:95:21)
at ArangoCollection.ensureIndex (.../arango-collection.js:733:12)
at <shell command>:1:3
127.0.0.1:8529@_system> c.ensureIndex(
...> {"type":"skiplist","unique":true,"fields":["abc"]})
JavaScript exception in file '.../arangosh.js' at 97,7:
ArangoError 1210: unique constraint violated
! throw error;
! ^
stacktrace: ArangoError: unique constraint violated
at Object.exports.checkRequestResult (.../arangosh.js:95:21)
at ArangoCollection.ensureIndex (.../arango-collection.js:733:12)
at <shell command>:1:3
与尝试插入违反唯一约束的文档类似:
127.0.0.1:8529@_system> db._drop("c")
127.0.0.1:8529@_system> c = db._create("c")
[ArangoCollection 315, "c" (type document, status loaded)]
127.0.0.1:8529@_system> c.ensureIndex({
...>"type":"skiplist","unique":true,"fields":["abc"]})
{
"id" : "c/318",
"type" : "skiplist",
"fields" : [
"abc"
],
"unique" : true,
"sparse" : false,
"isNewlyCreated" : true,
"code" : 201
}
127.0.0.1:8529@_system> c.insert({"abc":1})
{
"_id" : "c/330",
"_key" : "330",
"_rev" : "_T1n-B2S---"
}
127.0.0.1:8529@_system> c.insert({"abc":1})
JavaScript exception in file '.../arangosh.js' at 97,7:
ArangoError 1210: cannot create document, unique constraint violated
! throw error;
! ^
stacktrace: ArangoError: cannot create document, unique constraint violated
at Object.exports.checkRequestResult (.../arangosh.js:95:21)
at ArangoCollection.save.ArangoCollection.insert
(.../arango-collection.js:978:14)
at <shell command>:1:3
因此,如果您在创建索引之前在应用程序设置期间插入文档(出于性能原因,这是一种可行的方法),您需要在之后创建这些索引时处理可能的异常。