[英]Consume the results of Neo4j driver in java
Using Neo4j driver for java, i want to send a search query to the database such as:使用 Java 的 Neo4j 驱动程序,我想向数据库发送搜索查询,例如:
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:首先,我创建一个会话,然后使用驱动程序的 run 方法来运行查询:
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?
我的问题是如何使用记录以便将它们转换为 java 对象? 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.
我试图获取结果的值,但由于它们不可迭代,因此不可能一一获取它们。
Result
implements Iterator<Record>
, so there is a bunch of ways of consuming it, eg: Result
实现了Iterator<Record>
,所以有很多使用它的方法,例如:
While loop (Java 6 style): While 循环(Java 6 风格):
Result result = session.run(query);
List<MyPojo> myList = new ArrayList<>();
while(result.hasNext()) {
Record r = result.next();
myList.add(mapToMyPojo(r));
}
Stream (Java 8+ style):流(Java 8+ 风格):
Result result = session.run(query);
List<MyPojo> myList = result.stream()
.map(record -> mapToMyPojo(record))
.collect(Collectors.toList());
Using Result.list(Function<Record,T> mapFunction) :使用Result.list(Function<Record,T> mapFunction) :
Result result = session.run(query);
List<MyPojo> myList = result.list(r -> mapToMyPojo(r));
Mapping to a Java object is pretty stright-forward:映射到 Java 对象非常简单:
public MyPojo mapToMyPojo(Record record) {
MyPojo pojo = new MyPojo();
pojo.setProperty(record.get("Property").asString());
// ...
return pojo;
}
Although instead of mapping results manually, you might want to use neo4j-ogm虽然不是手动映射结果,但您可能希望使用neo4j-ogm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.