与现有节点建立关系 Cypher Neo4j

Create relation with existing nodes Cypher Neo4j

我正在创建一个带有唯一 Source 标签的关系图。我想知道是不是每次我第一次创建节点后都必须检查源或目标是否已经存在?

如果我在源存在但目标是新的情况下使用合并,则合并无法创建节点。我想创建以下图表。

我使用以下代码使用 JAVA

    String CQL = "CREATE (source:Source {hashtag: '1'})-[:TIMELINE {weight: 3, date: '1417132800'}]->(target:Target {hashtag: '2'})";
    ExecutionEngine execEngine = new ExecutionEngine(graphDb, StringLogger.DEV_NULL);
    ExecutionResult execResult = execEngine.execute(CQL);
    String results = execResult.dumpToString();
    System.out.println(results);

其次,请指导我如何从 ExecutionResult execResult = execEngine.execute(CQL); 中获取 json 以在 d3.js 中创建地图

我必须遵循 CQL 运行。

    CREATE CONSTRAINT ON (label:Source) ASSERT label.hashtag IS UNIQUE

    // if source and target are new
    CREATE (source:Source {hashtag: '1'})-[:TIMELINE {weight: 3, date: "1417132800"}]->(target:Target {hashtag: '2'})

    // if source and target are already created and have another TIMELINE relation
    MATCH (source:Source {hashtag: '1'}),(target:Target {hashtag: '2'}) CREATE (source)-[:TIMELINE {weight: 15, date: "1417132200"}]->(target)

    // if source already exists but target is new
    MATCH (source:Source {hashtag: '1'}) CREATE (source)-[:TIMELINE {weight: 20, date: "1417133200"}]->(target:Target {hashtag: '3'})

    // if source is new but target already exists
    MATCH (target:Target {hashtag: '2'}) CREATE (target)<-[:TIMELINE {weight: 30, date: "1417133400"}]-(source:Source {hashtag: '4'})

不太明白你的意思

f I use Merge when source is exists but target is new then merge failed to create node.

MERGE 应该以简约的方式使用。如果找不到 MERGE 中指定的路径的单个项目,则会创建 whole 模式。也就是说,如果你想最终创建起始节点、结束节点和它们之间的关系,请使用

MERGE (source:Source{hashtag:'1'})
MERGE (target:Source{hashtag:'3'})
MERGE (source)-[:TIMELINE {weight: 30, date: "1417133400"}]->(target)

关于您的第二个问题:创建 JSON

如果您将使用模型切换到 运行 Neo4j 服务器并使用 transactional Cypher endpoint,您将直接返回 JSON。

如果您想直接从 Java 代码呈现 JSON,请使用通常的嫌疑人,例如Google's GSON