Neo4j根据嵌套列表中的位置从JSON数据创建关系

时间:2018-07-12 23:02:39

标签: json neo4j cypher

我在JSON文件中有一些数据:

{"title": "Title1", "authors": [{"name": "John Mulaney", "org": "Stanford"}, {"name": "Dave Chappelle", "org": "MIT"}, {"name": "Kurt Warner", "org": "UCSB"}, {"name": "Hulk Hogan", "org": "UCSD"}], "id": "abc123"}
{"title": "Title2", "authors": [{"name": "Rick Sanchez", "org": "MIT"}, {"name": "Amy Schumer", "org": "Harvard"}], "id": "xyz234"}

具体来说,我想向作者和论文之间的每个关系添加一个属性,该属性与作者列表中作者的位置相对应-该属性看起来像 "position":"first_author", "position":"second_author", etc and the last author is "position":"last_author".

每篇论文的作者数量都是可变的。

以下Cypher命令为论文和作者创建节点,并在它们之间创建关系。

CALL apoc.load.json('file.txt') YIELD value AS q UNWIND q.id AS id UNWIND q.authors as authors 
MERGE (a:Author {name:authors.name})
MERGE (p:Paper {id:q.id}) ON CREATE SET p.title=q.title
CREATE (a)-[:AUTHORED]->(p)

当作者数量可变时,如何跟踪作者列表中的位置并将其添加为关系的属性?

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

首先,为了优化您的查询,我更喜欢将MERGE的{​​{1}}放在Paper的循环之外:

Author

要回答您的问题,您需要创建作者职位的索引。为此,我将使用:CALL apoc.load.json('file.txt') YIELD value AS q UNWIND q.id AS id MERGE (p:Paper {id:q.id}) ON CREATE SET p.title=q.title WITH p, q UNWIND q.authors as authors MERGE (a:Author {name:authors.name}) CREATE (a)-[:AUTHORED]->(p)

例如,range(0, size(q.authors), 1) AS index为此RETURN range(0, 10, 1) AS index

最后,这是搜索到的查询:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
相关问题