使用c#中的Neo4jClient在Neo4j中创建节点之间的关系
本文关键字:节点 创建 之间 关系 Neo4j 中的 Neo4jClient 使用 | 更新日期: 2023-09-27 17:51:13
我使用。net Neo4jClient (http://hg.readify.net/neo4jclient/wiki/Home)与Neo4j一起工作。在我的代码中,节点是机场,关系是航班。
如果我想同时创建节点和关系,我可以使用以下代码:
public class Airport
{
public string iata { get; set; }
public string name { get; set; }
}
public class flys_toRelationship : Relationship, IRelationshipAllowingSourceNode<Airport>, IRelationshipAllowingTargetNode<Airport>
{
public static readonly string TypeKey = "flys_to";
// Assign Flight Properties
public string flightNumber { get; set; }
public flys_toRelationship(NodeReference targetNode)
: base(targetNode)
{ }
public override string RelationshipTypeKey
{
get { return TypeKey; }
}
}
主要// Create a New Graph Object
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
// Create New Nodes
var lax = client.Create(new Airport() { iata = "lax", name = "Los Angeles International Airport" });
var jfk = client.Create(new Airport() { iata = "jfk", name = "John F. Kennedy International Airport" });
var sfo = client.Create(new Airport() { iata = "sfo", name = "San Francisco International Airport" });
// Create New Relationships
client.CreateRelationship(lax, new flys_toRelationship(jfk) { flightNumber = "1" });
client.CreateRelationship(lax, new flys_toRelationship(sfo) { flightNumber = "2" });
client.CreateRelationship(sfo, new flys_toRelationship(jfk) { flightNumber = "3" });
但是,当我想向已经存在的节点添加关系时,问题就出现了。假设我有一个仅由两个节点(机场)组成的图,比如SNA和EWR,我想添加一个从SNA到EWR的关系(航班)。我尝试了以下操作,但失败了:
// Create a New Graph Object
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
Node<Airport> departure = client.QueryIndex<Airport>("node_auto_index", IndexFor.Node, "iata:sna").First();
Node<Airport> arrival = client.QueryIndex<Airport>("node_auto_index", IndexFor.Node, "iata:ewr").First();
//Response.Write(departure.Data.iata); <-- this works fine, btw: it prints "sna"
// Create New Relationships
client.CreateRelationship(departure, new flys_toRelationship(arrival) { flightNumber = "4" });
我收到的两个错误如下:
1)参数1:不能从"Neo4jClient"转换。节点'到'Neo4jClient '。NodeReference '
方法"Neo4jClient. graphclient . createrrelationship (Neo4jClient. graphclient . createrrelationship)"的类型参数。noderreference, TRelationship)'不能从用法中推断出来。尝试显式指定类型参数。错误引用的方法在以下类中:http://hg.readify.net/neo4jclient/src/2c5446c17a65d6e5accd420a2dff0089799cbe16/Neo4jClient/GraphClient.cs?at=default
任何想法?
在您的CreateRelationship
调用中,您将需要使用节点引用,而不是节点,因此:
client.CreateRelationship(departure.Reference, new flys_toRelationship(arrival.Reference) { flightNumber = "4" });
为什么你的初始创建代码工作,这没有是因为Create
返回给你一个NodeReference<Airport>
(var
为你隐藏),而QueryIndex
返回一个Node<Airport>
实例。
Neo4jClient主要使用NodeReference
的大部分操作。
第二个错误与没有使用.Reference
属性有关,因为它不能确定类型,当你使用.Reference
属性时,这个错误也会消失。