Search code examples
insertorientdbupsert

Getting @rid while Update-Upsert in OrientDB without searching again


I am currently using OrientDB to build a graph model. I am using PyOrient to send commands for creating the nodes and edges.

Whenever I use INSERT command I get a list of things which includes @rid in return.

result = db.command("INSERT INTO CNID SET connected_id {0}".format(somevalue))

print result

OUTPUT: {'@CNID':{'connected_id': '10000'},'version':1,'rid':'#12:1221'}

However if I use the Update-Upsert command I only get one value as return which is not the @rid.

result = db.command("UPDATE CNID SET connected_id={0} UPSERT WHERE connected_id={0}".format(cn_value)) print result

OUTPUT: 1

I want to know is it possible to get @rid as well while doing UPDATE-UPSERT operation.


Solution

  • I created the following example in PyOrient:

    Structure:

    enter image description here

    A useful method to retrieve the @rid from an UPDATE / UPSERT operation could be the usage of the RETURN AFTER $current syntax in your SQL command.

    PyOrient Code:

    import pyorient
    
    
    db_name = 'Stack37308500'
    
    print("Connecting to the server...")
    client = pyorient.OrientDB("localhost",2424)
    session_id = client.connect("root","root")
    print("OK - sessionID: ",session_id,"\n")
    
    if client.db_exists( db_name, pyorient.STORAGE_TYPE_PLOCAL ):
        client.db_open(db_name, "root", "root")
        result = client.command("UPDATE CNID SET connected_id = 20000 UPSERT RETURN AFTER $current.@rid WHERE connected_id = 20000")
        for idx, val in enumerate(result):
            print(val)
    
    client.db_close() 
    

    By specifying $current.@rid you'll be able to retrieve the @rid of the resulting record (in this case a new record).

    Code Output:

    Connecting to the server...
    OK - sessionID:  25 
    
    ##12:1
    

    Studio:

    enter image description here

    You can also modify the query to retrieve the whole resulting record by use only $current without specifying @rid (in this case I updated the record #12:1).

    Query:

    UPDATE CNID SET connected_id = 30000 UPSERT RETURN AFTER $current WHERE connected_id = 20000
    

    Code Output:

    Connecting to the server...
    OK - sessionID:  26 
    
    {'@CNID':{'connected_id': 30000},'version':2,'rid':'#12:1'}
    

    Studio:

    enter image description here

    Hope it helps