简体   繁体   English

如何正确地使用唯一索引字段更新ArangoDB文档?

[英]How to properly update an ArangoDB document with unique index field?

I have the following schema for users table: 我为用户表具有以下架构:

   name: string
   emails: [string] // unique index

The index is created in the following way (in go language): 索引以以下方式(使用go语言)创建:

usersCollection.EnsureHashIndex(
    ctx, 
    []string{"emails[*]"}, 
    driver.EnsureHashIndexOptions{Unique: true, Sparse: true})

Let's say I have the following user in the DB: 假设我在数据库中有以下用户:

{_key: "1", name: "A", emails: ["aa@aa.aa"]}

Adding an email using the following command in arangosh returns an error: arangosh使用以下命令添加电子邮件arangosh返回错误:

> db.users.update("1", {emails: ["aa@aa.aa", "aa2@aa.aa"]})
JavaScript exception in file '/usr/share/arangodb3/js/client/modules/@arangodb/arangosh.js' at 99,7: ArangoError 1210: unique constraint violated - in index 442818 of type rocksdb-hash over ["emails[*]"]; conflicting key: 1

Using replace returns similar error. 使用replace返回类似的错误。

How can I properly add an email to the given user? 如何正确向给定用户添加电子邮件?

I'm demonstrating this in arangosh. 我正在arangosh演示这个。 Creating the collection: 创建集合:

db._create('usersCollection')
[ArangoCollection 497, "usersCollection" (type document, status loaded)]

Add the unique index to the collection: 将唯一索引添加到集合中:


db.usersCollection.ensureIndex({ type: "hash", fields: [ "emails[*]" ], unique: true, sparse: true })
{ 
  "deduplicate" : true, 
  "fields" : [ 
    "emails[*]" 
  ], 
  "id" : "usersCollection/517", 
  "isNewlyCreated" : true, 
  "selectivityEstimate" : 1, 
  "sparse" : true, 
  "type" : "hash", 
  "unique" : true, 
  "code" : 201 
}

Create the entry as you did: 像您一样创建条目:

 db.usersCollection.save({_key: "1", name: "A", emails: ["aa@aa.aa"]})
{ 
  "_id" : "usersCollection/1", 
  "_key" : "1", 
  "_rev" : "_YSk15je---" 
}

Now we use AQL to update the emails field to add the other email: 现在,我们使用AQL更新电子邮件字段以添加其他电子邮件:

db._query(`UPDATE '1' WITH {emails: ["aa@aa.aa", "bb@bb.bb"]} IN usersCollection`)
[object ArangoQueryCursor, count: 0, cached: false, hasMore: false]

Inspecting the reply: 检查回复:

db.usersCollection.toArray()
[ 
  { 
    "_key" : "1", 
    "_id" : "usersCollection/1", 
    "_rev" : "_YSk2J1K--_", 
    "name" : "A", 
    "emails" : [ 
      "aa@aa.aa", 
      "bb@bb.bb" 
    ] 
  } 
]

Apparently this is a bug in ArangoDB and will be solved later on: 显然,这是ArangoDB中的错误,稍后会解决:

https://github.com/arangodb/arangodb/issues/8359 https://github.com/arangodb/arangodb/issues/8359

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM