UPSERTing with TitanDB

后端 未结 2 1796
小蘑菇
小蘑菇 2021-01-23 17:09

I\'m having my first steps as a TitanDB user. That being, I\'d like to know how to make an upsert / conditionally insert a vertex inside a TitanTransaction (in the

相关标签:
2条回答
  • 2021-01-23 17:16

    Here's a one-liner "getOrCreate" for Titan 1.0 and TinkerPop 3:

    getOrCreate = { id ->
      g.V().has('userId', id).tryNext().orElseGet{ g.addV('userId', id).next() }
    }
    

    As taken from the new TinkerPop "Getting Started" Tutorial. Here is the same code translated to java:

    public Vertex getOrCreate(Object id) {
      return g.V().has('userId', id).tryNext().orElseGet(() -> g.addV('userId', id).next());
    }
    
    0 讨论(0)
  • 2021-01-23 17:35

    Roughly speaking, every Cassandra insert is an "upsert". If you look at the Titan representation of vertices and edges in a Cassandra-like model, you'll find vertices and edges each get their own rows. This means a blind write of an edge will have the given behavior you're looking for: what you write is what will win. Doing this with a vertex isn't supported directly by Titan.

    But I don't think this is what you're looking for. If you're looking to enforce uniqueness, why not use the unique() modifier on a Titan composite index? (From the documentation):

    mgmt.buildIndex('byNameUnique', Vertex.class).addKey(name).unique().buildCompositeIndex()
    

    With a Cassandra storage backend, you need to enable consistency locking. As with any database, managing the overhead of uniqueness comes at a cost which you need to consider when writing your data. This way if you insert a vertex which violates your uniqueness requirement, the transaction will fail.

    0 讨论(0)
提交回复
热议问题