mano haran
mano haran

Reputation: 89

How to increment or decrement a value of vertex property in gremlin

For Example this is my Vertex:

[label:songs, id:4336, name:testsong123, likeCount:0 ]

What I have to do:

I want to increment the "likeCount" when ever user likes the song and decrement the "likeCount" whenever a user unlike the song.

What I am doing now:

By default how I am doing is to get the vertex by id and add "+1" to "likeCount",then update to database.similar for decrement,add -1 to the "likeCount" and update to database.

Alternative: Is there any way to just increment or decrement without a get call.

Upvotes: 1

Views: 467

Answers (2)

Min Su Byun
Min Su Byun

Reputation: 11

Here's a DSL I've written in Java, I think you can do a similar thing.

valueTraversal can be replaced with constant(1), or traversal.count().

public default GraphTraversal<S, ?> incrementProperty(final String propertyKey,
        final GraphTraversal<?,?> valueTraversal) {
    return property(Cardinality.single, propertyKey,
            __.union(
                __.values(propertyKey),
                valueTraversal)
            .sum());
}

public default GraphTraversal<S, ?> decrementProperty(final String propertyKey,
        final GraphTraversal<?,?> valueTraversal) {
    return property(Cardinality.single, propertyKey,
            __.union(
                __.values(propertyKey),
                valueTraversal).math("_ * -1")
            .sum());
}

Upvotes: 1

stephen mallette
stephen mallette

Reputation: 46226

If you don't have a reference to the vertex, then you have little choice but to look it up (i.e. get it). The lookup should not be a large problem as you intend to lookup by id which should not be very expensive.

Upvotes: 4

Related Questions