如何使用Transaction函数正确返回StatementResult?

时间:2019-01-03 10:15:51

标签: java neo4j driver

也许标题本身足以表达我的困惑。一方面,我读到很多文章,推荐使用事务功能来使用neo4j java驱动程序。

请参见Neo4j Java Driver

另一方面,我看到了代码示例,例如在Neo4j Java Driver 1.7 API中没有事务(或者可能是隐式的),我喜欢拥有StatementResult并在其上进行迭代的想法。它。

那我该怎么办?

在事务功能中是否有自动提交事务的迭代器的方法?我应该继续使用execute()函数还是session.writeTransaction()函数吗?

在我看来,有很多方法可以运行一个简单的请求,但无法弄清楚原因,或者这些方法是否可以混在一起。

如果我只能从其中得到一个字符串,我对writeTransaction不太满意。

此驱动程序也有GitHub examples,尤其是the ResultRetain,带有'Record'对象,它与我要查找的对象更接近,但没有任何迭代器。它允许使用访问者提取数据。另一个比较接近的例子是ResultConsume,但仍然没有迭代器。

基于这些示例,我编写了以下代码,它可以与生成器和获取器一起正常工作。

import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;


public class InitializeUser extends Logger{
  StatementResult result;

  public void getUserForInitialization(){
    try ( Session session = driver.session() )
    {
      result = session.readTransaction( new TransactionWork<StatementResult>()
        {
            @Override
            public StatementResult execute( Transaction tx )
            {
                return tx.run(
                  "MATCH (a{initialized:false}) "+
                  "RETURN a.username as username");
            }
        } );
    }
  }

  public void readGenerator(){
    while (result.hasNext())
    {
        Record record = result.next();
        System.out.println(record.get("username").asString());
    }
  }
}

我不确定是否比遵循ResultRetainResultConsume示例更糟或更出色,但是它具有生成器,获取器以及我认为的事务处理功能。我仍然非常乐意接受建议和解释。

如果有人可以解释一下TransactionWork()execute()背后的机制,以及readTransaction()writeTransaction()run()和{{ 1}},我很高兴。


Neo4j Java驱动程序

beginTransaction()

Neo4j Java驱动程序1.7 API

import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;

import static org.neo4j.driver.v1.Values.parameters;

public class HelloWorldExample implements AutoCloseable
{
    private final Driver driver;

    public HelloWorldExample( String uri, String user, String password )
    {
        driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
    }

    @Override
    public void close() throws Exception
    {
        driver.close();
    }

    public void printGreeting( final String message )
    {
        try ( Session session = driver.session() )
        {
            String greeting = session.writeTransaction( new TransactionWork<String>()
            {
                @Override
                public String execute( Transaction tx )
                {
                    StatementResult result = tx.run( "CREATE (a:Greeting) " +
                                                     "SET a.message = $message " +
                                                     "RETURN a.message + ', from node ' + id(a)",
                            parameters( "message", message ) );
                    return result.single().get( 0 ).asString();
                }
            } );
            System.out.println( greeting );
        }
    }

    public static void main( String... args ) throws Exception
    {
        try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
        {
            greeter.printGreeting( "hello, world" );
        }
    }
}

Neo4j Java驱动程序ResultRetainExample

import org.neo4j.driver.v1.*;

import static org.neo4j.driver.v1.Values.parameters;

public class SmallExample
{
    // Driver objects are thread-safe and are typically made available application-wide.
    Driver driver;

    public SmallExample(String uri, String user, String password)
    {
        driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
    }

    private void addPerson(String name)
    {
        // Sessions are lightweight and disposable connection wrappers.
        try (Session session = driver.session())
        {
            // Wrapping Cypher in an explicit transaction provides atomicity
            // and makes handling errors much easier.
            try (Transaction tx = session.beginTransaction())
            {
                tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
                tx.success();  // Mark this write as successful.
            }
        }
    }

    private void printPeople(String initial)
    {
        try (Session session = driver.session())
        {
            // Auto-commit transactions are a quick and easy way to wrap a read.
            StatementResult result = session.run(
                    "MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
                    parameters("x", initial));
            // Each Cypher execution returns a stream of records.
            while (result.hasNext())
            {
                Record record = result.next();
                // Values can be extracted from a record by index or name.
                System.out.println(record.get("name").asString());
            }
        }
    }

    public void close()
    {
        // Closing a driver immediately shuts down all open connections.
        driver.close();
    }

    public static void main(String... args)
    {
        SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
        example.addPerson("Ada");
        example.addPerson("Alice");
        example.addPerson("Bob");
        example.printPeople("A");
        example.close();
    }
}

Neo4j Java驱动程序ResultConsumeExample

import java.util.List;

import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;

import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import[]

public class ResultRetainExample extends BaseApplication
{
    public ResultRetainExample( String uri, String user, String password )
    {
        super( uri, user, password );
    }

    // tag::result-retain[]
    public int addEmployees( final String companyName )
    {
        try ( Session session = driver.session() )
        {
            int employees = 0;
            List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
            {
                @Override
                public List<Record> execute( Transaction tx )
                {
                    return matchPersonNodes( tx );
                }
            } );
            for ( final Record person : persons )
            {
                employees += session.writeTransaction( new TransactionWork<Integer>()
                {
                    @Override
                    public Integer execute( Transaction tx )
                    {
                        tx.run( "MATCH (emp:Person {name: $person_name}) " +
                                "MERGE (com:Company {name: $company_name}) " +
                                "MERGE (emp)-[:WORKS_FOR]->(com)",
                                parameters( "person_name", person.get( "name" ).asString(), "company_name",
                                        companyName ) );
                        return 1;
                    }
                } );
            }
            return employees;
        }
    }

    private static List<Record> matchPersonNodes( Transaction tx )
    {
        return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
    }

    // end::result-retain[]

}

0 个答案:

没有答案