【问题标题】:In Gremlin, how do I modify a vertex's properties only if a version property matches a number?在 Gremlin 中,仅当版本属性与数字匹配时,如何修改顶点的属性?
【发布时间】:2019-10-22 23:51:55
【问题描述】:

在 Gremlin/Tinkerpop 中,我想在 Vertex 上执行版本化 upsert。如果存在现有 Vertex,我只想在版本与版本号属性匹配时对其进行变异。

下面是尝试使用gremlinjs 执行此操作的代码。创建顶点失败,后续查询找不到。

(之前的版本有一个编译错误,但这是一个 javscriptism 未记录的语法问题)

[更新] 请参阅 cmets 以了解问题所在。 工作版本https://gist.github.com/pszabop/3b07fa7caadf1dbd86953a713ed96ce0

//
// o.id o.__version, and o.__lastUpdate have special meaning or are reserved
//
graphdb.upsertVertexVersioned = async function(type, o) {
  const g = traversal().withRemote(this.connection);
  let oldVersion;

  if (!o.id) {
    o.id = uuidv4();
  }  
  if (!o.__version) {
    o.__version = 0;
    oldVersion = 0;
  } else {
    oldVersion = o.__version;
    o.__version++;
  }  
  o.__lastUpdate = Date.now();

  // @see http://tinkerpop.apache.org/docs/current/recipes/#element-existence
  // The pattern we are using is keys get copied into properties that can be used
  // by the graph database for its work, and then the
  // entire object is JSON serialized into a generic `obj` property.
  // XXX TBD use graphson?
  const v1 = await g.V().has(type, 'id', o.id) 
  .fold()  
  .coalesce(__.unfold(),
    __.addV(type).property('id', o.id)                       
    .property('version', o.__version)                        
  ).choose(__.values('version').is(oldVersion),
    __.in_() 
    .property('lastUpdate', o.__lastUpdate)                  // updated properties go here
    .property('version', o.__version)                        // updated properties go here
    .property('obj', JSON.stringify(o)),                     // updated properties go here
    __.out()
  ).next();

  return o;
};

参考资料:

版本

  • janusgraph/janusgraph:最新
  • gremlinjs 3.4.4

【问题讨论】:

    标签: gremlin tinkerpop janusgraph gremlinjs


    【解决方案1】:

    我使用“现代”玩具图尝试了您的代码的变体,结果证明您的代码对我来说是正确的。我相信以下内容体现了您所做工作的精神:

    gremlin> g = TinkerFactory.createModern().traversal()
    ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
    gremlin> g.V().property('version',1).iterate()
    gremlin> name = 'marko'
    ==>marko
    gremlin> oldVersion = 1
    ==>1
    gremlin> version = 2
    ==>2
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>edited
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>same
    gremlin> name = 'stephen'
    ==>stephen
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>same
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>same
    gremlin> oldVersion = 2
    ==>2
    gremlin> version = 3
    ==>3
    gremlin> 
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>edited
    gremlin> g.V().has('person','name',name).
    ......1>   fold().
    ......2>   coalesce(unfold(), 
    ......3>            addV('person').property('name',name).property('version',version)).
    ......4>   choose(values('version').is(oldVersion),
    ......5>          property('version', version).constant('edited'),
    ......6>          constant('same'))
    ==>same
    gremlin> g.V().has('person','name','stephen').elementMap()
    ==>[id:19,label:person,name:stephen,version:3]
    

    鉴于您对问题的描述,我建议您尝试简化一下。你说的问题是:

    创建顶点失败,后续查询找不到。

    如果你删除choose() 逻辑,它是否可以正常工作?换句话说,你能让基本的 upsert 操作工作吗?如果不是,那么问题似乎与查询的那部分无关,尽管您所拥有的似乎遵循推荐的做法,所以我不确定可能有什么问题。

    【讨论】:

    • 谢谢你,你的例子让我发现使用__.in() 是为了遍历边缘,我应该做的只是继续修改,例如__.property('version', o.__version)...gist.github.com/pszabop/3b07fa7caadf1dbd86953a713ed96ce0测试工作版本的要点@
    • @PaulS — 很高兴听到您解决了问题!您能否将您的要点转移到一个单独的答案中并接受它,以便可以将此问题标记为已回答?谢谢!
    【解决方案2】:

    gremlinjs 中的以下代码仅在版本号属性匹配时才更新顶点。这允许使用 乐观并发 对顶点进行安全的读-修改-写(即冲突应该很少见,或者您应该做其他事情)

    代码可用作要点:https://gist.github.com/pszabop/3b07fa7caadf1dbd86953a713ed96ce0

    //
    // o.id o.__version, and o.__lastUpdate have special meaning or are reserved
    //
    graphdb.upsertVertexVersioned = async function(type, o) {
      const g = traversal().withRemote(this.connection);
      let oldVersion;
    
      // don't modify original in case of exceptions
      // return the new object and let user decide to reassign or not
      o = Object.assign({}, o);
    
      if (!o.id) {
        o.id = uuidv4();
      }
      if (!Number.isInteger(o.__version)) {
        o.__version = 0;
        oldVersion = 0;
      } else {
        oldVersion = o.__version;
        o.__version++;
      }
      o.__lastUpdate = Date.now();
    
      // @see http://tinkerpop.apache.org/docs/current/recipes/#element-existence
      // @see https://stackoverflow.com/questions/58513680/in-gremlin-how-do-i-modify-a-vertexs-properties-only-if-a-version-property-mat
      // The pattern we are using is keys get copied into properties that can be used
      // by the graph database for its work, and then the
      // entire object is JSON serialized into a generic `obj` property.
      // XXX TBD use graphson?
      const v1 = await g.V().has(type, 'id', o.id)
      .fold()
      .coalesce(__.unfold(),
        __.addV(type).property('id', o.id)
        .property('version', o.__version)
      ).choose(__.values('version').is(oldVersion),
        __.property('lastUpdate', o.__lastUpdate)                  // updated properties go here
        .property('version', o.__version)
        .property('obj', JSON.stringify(o)).constant('edited'),
        __.constant('unchanged')
      ).next();
    
      if (v1.value === 'unchanged') {
        throw new Error('version mismatch, vertex not updated');
      }
    
      return o;
    };
    
    test('test vertex versioned upsert and get', async function(t) {
    
      graphdb.open();
    
      // initial write and verify
      const o = { randomText: uuidv4(), foo: 'bar'}
      const osent1 = await graphdb.upsertVertexVersioned('testtype', o);
      t.ok(osent1.id, 'a random ID was assigned');
      const oget1 = await graphdb.getVertex('testtype', osent1.id);
      t.equal(oget1.randomText, o.randomText, 'random text was as written');
      t.equal(oget1.id, osent1.id, 'ID was as assigned');
      t.equal(oget1.foo, 'bar', 'field foo is "bar"');
    
      // make sure version gets updated when field foo is modified
      oget1.foo = 'beyond all repair';
      const osent2 = await graphdb.upsertVertexVersioned('testtype', oget1);
      t.equal(osent2.__version, 1, 'version was changed from 0 to 1');
      const oget2 = await graphdb.getVertex('testtype', oget1.id);
      t.equal(oget2.randomText, o.randomText, 'random text was as written and was unchanged on second write');
      t.equal(oget2.id, osent1.id, 'ID was as assigned');
      t.equal(oget2.foo, 'beyond all repair', 'field foo was changed to "beyond all repair"');
    
      // if we are using a stale copy of the object an update should not happen
      osent1.foo = 'illegal update';
      try {
        const osent3 = await graphdb.upsertVertexVersioned('testtype', osent1);
        t.fail('should never returned from an incorrect version update');
      } catch (err) {
        t.ok(err.toString().includes('not updated'), 'error message is correct on illegal version update attempt');
      }
      const oget3 = await graphdb.getVertex('testtype', oget1.id);
      t.equal(oget3.randomText, o.randomText, 'random text was as written and was unchanged on second write');
      t.equal(oget3.id, osent1.id, 'ID was as assigned');
      t.equal(oget3.foo, 'beyond all repair', 'field foo was unchanged after failed update');
      graphdb.close();
    
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多