消费 Neo4j 驱动在 Java 中的结果

huangapple go评论73阅读模式
英文:

Consume the results of Neo4j driver in java

问题

使用Neo4j Java驱动程序,我想向数据库发送一个搜索查询,类似于:

MATCH(a:`Label`{Property:"NODE_PROPERTY"})
RETURN *

首先,我创建一个会话,然后使用驱动程序的run方法运行查询:

Result run = session.run(query);

run变量包含一系列记录(Records)。我的问题是如何消耗这些记录,以便我可以将它们转换为Java对象?我尝试过获取结果的值,但由于它们不可迭代,无法逐个获取。

英文:

Using Neo4j driver for java, i want to send a search query to the database such as:

MATCH(a:`Label`{Property:"NODE_PROPERTY"})
RETURN *

First i create a session and the i use the run methods of the driver to run a query:

Result run = session.run(query);

run variable contains a list of Records. My question is how can i consume the records so that i can convert them to java objects? I tried to get the values of the results but since they're not iterable, it's not possible to get them one by one.

答案1

得分: 1

Result 实现了 Iterator<Record> 接口,因此有许多方法可以使用它,例如:

While 循环(Java 6 风格):

Result result = session.run(query);
List<MyPojo> myList = new ArrayList<>();
while(result.hasNext()) {
    Record r = result.next();
    myList.add(mapToMyPojo(r));
}

流式操作(Java 8+ 风格):

Result result = session.run(query);
List<MyPojo> myList = result.stream()
    .map(record -> mapToMyPojo(record))
    .collect(Collectors.toList());

使用 Result.list(Function<Record,T> mapFunction)

Result result = session.run(query);
List<MyPojo> myList = result.list(r -> mapToMyPojo(r));

将结果映射到 Java 对象非常直观:

public MyPojo mapToMyPojo(Record record) {
    MyPojo pojo = new MyPojo();
    pojo.setProperty(record.get("Property").asString());
    // ...
    return pojo;
}

虽然您可以手动映射结果,但也可以考虑使用 neo4j-ogm

英文:

Result implements Iterator&lt;Record&gt;, so there is a bunch of ways of consuming it, e.g.:

While loop (Java 6 style):

Result result = session.run(query);
List&lt;MyPojo&gt; myList = new ArrayList&lt;&gt;();
while(result.hasNext()) {
    Record r = result.next();
    myList.add(mapToMyPojo(r));
}

Stream (Java 8+ style):

Result result = session.run(query);
List&lt;MyPojo&gt; myList = result.stream()
    .map(record -&gt; mapToMyPojo(record))
    .collect(Collectors.toList());

Using Result.list(Function<Record,T> mapFunction):

Result result = session.run(query);
List&lt;MyPojo&gt; myList = result.list(r -&gt; mapToMyPojo(r));

Mapping to a Java object is pretty stright-forward:

public MyPojo mapToMyPojo(Record record) {
    MyPojo pojo = new MyPojo();
    pojo.setProperty(record.get(&quot;Property&quot;).asString());
    // ...
    return pojo;
}

Although instead of mapping results manually, you might want to use neo4j-ogm

huangapple
  • 本文由 发表于 2020年9月26日 19:53:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64077379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定