假设我有一个相当大的JSON对象。此对象可以以多种方式嵌套,并包含数组。该对象为我提供了一个用户及其与一个类型的单个对象和一个类型的多个(数组)对象的关系。
我的目标是尽可能快速有效地将其插入到Neo4j中。
是否可以这样做,并建议在一个查询中执行迭代JSON结构创建的串联字符串? (解析对象并抽象成多个节点和关系)
这也是一个让我难以理解这个过程的常见问题: 对于我迭代的数组,当我连接MERGE语句时,Neo4J中的节点会重复,并且合并似乎不起作用。
//Person to interests
_.each(interests, function(itr){
ingestQuery += 'MERGE(centerRep)-[:INTERESTED_IN]->(:Interest{name: "'+itr.interest_name+'", category: "'+itr.interest_category+'"})'
},this)
因此,如果此语句运行两次,则兴趣节点将被创建两次,这是不需要的行为。
答案 0 :(得分:1)
您可以将JSON作为参数传递给Cypher查询,并使用UNWIND
迭代JSON中的数组。
例如(取自this blog post),假设你的JSON看起来像这样:
{ "items": [{
"question_id": 24620768,
"link": "http://stackoverflow.com/questions/24620768/neo4j-cypher-query-get-last-n-elements",
"title": "Neo4j cypher query: get last N elements",
"answer_count": 1,
"score": 1,
.....
"creation_date": 1404771217,
"body_markdown": "I have a graph....How can I do that?",
"tags": ["neo4j", "cypher"],
"owner": {
"reputation": 815,
"user_id": 1212067,
....
"link": "http://stackoverflow.com/users/1212067/"
},
"answers": [{
"owner": {
"reputation": 488,
"user_id": 737080,
"display_name": "Chris Leishman",
....
},
"answer_id": 24620959,
"share_link": "http://stackoverflow.com/a/24620959",
....
"body_markdown": "The simplest would be to use an ... some discussion on this here:...",
"title": "Neo4j cypher query: get last N elements"
}]
}
将此JSON对象作为参数传递给Cypher查询以将其插入图形中,如下所示:
WITH {json} as data
UNWIND data.items as q
MERGE (question:Question {id:q.question_id}) ON CREATE
SET question.title = q.title, question.share_link = q.share_link, question.favorite_count = q.favorite_count
MERGE (owner:User {id:q.owner.user_id}) ON CREATE SET owner.display_name = q.owner.display_name
MERGE (owner)-[:ASKED]->(question)
FOREACH (tagName IN q.tags | MERGE (tag:Tag {name:tagName}) MERGE (question)-[:TAGGED]->(tag))
FOREACH (a IN q.answers |
MERGE (question)<-[:ANSWERS]-(answer:Answer {id:a.answer_id})
MERGE (answerer:User {id:a.owner.user_id}) ON CREATE SET answerer.display_name = a.owner.display_name
MERGE (answer)<-[:PROVIDED]-(answerer))
关于您的MERGE问题。 MERGE查看整个模式,并根据指定的整个模式“获取或创建”。通常,您希望在单个节点属性上进行MERGE,以确保节点不会重复而不是更大的模式。请查看this blog post的MERGE部分以获取更多详细信息。