goldengreen
goldengreen

Reputation: 23

Neo4J Cypher query equivalent to select for update

I have two instances of my application running.

Each one has a cypher query running on a scheduled job to grab the data for the DB and send it off to a service. Problem is that each instance grabs the data and sends it off, so duplicate data is received by the service.

What I have done so far is to have a property as a flag set to true when the data is matched/queried from the DB.

so my query is along the lines of:

Match (n) where sentData=false SET sentData=true return n.

I was hoping that the data would be locked by one instance with the SET in the MATCH query and the other instance would not be able to grab it or modify it, but it does and so still duplicate data is sent to the service.

In oracle, for example, I would do a "select for update" then one instance would grab the lock during the select and when doing an update one instance would do it and the other one would throw an exception.

I am only new to graph DB's so I apologies if the terminology is not fully correct. Thanks

Upvotes: 2

Views: 258

Answers (1)

cybersam
cybersam

Reputation: 67044

You can use one of the APOC atomic property update procedures to update the sentData property atomically.

For example, even if there is a race condition (such that both transactions see a false sentData), this query should ensure that only one transaction will return n:

MATCH (n:Foo)
WHERE NOT n.sentData
CALL apoc.atomic.update(n, 'sentData', 'true', 5) YIELD oldValue, newValue
WHERE apoc.convert.toBoolean(newValue) AND NOT apoc.convert.toBoolean(oldValue)
RETURN n

Upvotes: 1

Related Questions