【问题标题】:How to properly update an ArangoDB document with unique index field?如何正确更新具有唯一索引字段的 ArangoDB 文档?
【发布时间】:2019-02-28 00:52:29
【问题描述】:

我有以下用户表架构:

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

索引的创建方式如下(go 语言):

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

假设我在数据库中有以下用户:

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

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

使用replace 会返回类似的错误。

如何正确地向给定用户添加电子邮件?

【问题讨论】:

    标签: arangodb unique-constraint unique-index


    【解决方案1】:

    我正在用 arangosh 演示这一点。创建集合:

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

    将唯一索引添加到集合中:

    
    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 
    }
    

    像你一样创建条目:

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

    现在我们使用 AQL 更新电子邮件字段以添加其他电子邮件:

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

    检查回复:

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

    【讨论】:

    • 好的,但这适用于 AQL。是否可以使用集合 API 更新文档?例如使用.update.replace 函数?我来不及了。
    • 它应该也可以与.replace() 一起使用,但是在 3.4.x 中引入了一个错误,如果您尝试它会导致错误。该问题将在此 GitHub 问题中进行跟踪:github.com/arangodb/arangodb/issues/8359 作为一种解决方法,请将上述解决方案与 AQL 查询一起使用。
    【解决方案2】:

    显然这是 ArangoDB 中的一个错误,稍后会解决:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 2014-11-07
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多