问题
I have imported hierarchical data into OrientDB from RDMBS using OETL. In RDBMS we used to store parentId in the same row. e.g. the table structure is something like this:
ID - Name - Parent_ID
Corp - Corporate Office - Corp
D1 - District Office 1 - Corp
D2 - District Office 2 - Corp
SO1 - Small Office 1 - D1
SO2 - Small Office 2 - D2
SO3 - Small Office 3 - D1
Now each row is a node in Orientdb.
I want to create an edge (ParentOf) from say Corp to D1 and D1 to SO1 and so on.
How can I write a query to achieve this? Something along the line of following?
create edge parentOf from (select from node)a to (select from node where a.id = parent_id)
Sorry I am still thinking in relational db way.
Orient DB version is orientdb-community-2.0.9
回答1:
Thanks to pembeci, following is the function which finally did the trick:
var db = orient.getGraph();
var nodes = db.getVerticesOfClass("nodex");
var itr = nodes.iterator();
while(itr.hasNext()) {
var vertex = itr.next();
var id = vertex.getProperty("id");
var children = db.getVertices("parent_id", id);
var childItr = children.iterator();
while(childItr.hasNext()) {
var child = childItr.next();
vertex.addEdge("parentOf", child);
}
}
回答2:
You can't pass information from the first select query (from part) to the second query (to part). So you should possibly create a server side function. Something like this may work (I'll test it later, when I'll have access to Orient Studio):
var db = orient.getGraph;
var nodes = db.getVerticesOfClass("node");
for (var i=0; i<nodes.length; i++) {
var vertex = nodes[i]
var id = vertex.getProperty("id");
var children = db.getVertices("parent_id", id);
for (var j=0; j<children.length; j++) {
var child = children[j];
vertex.addEdge("parentOf", child)
}
}
回答3:
The js function was running forever. Finally wrote java code to do this:
OrientGraph graph = new OrientGraph("remote:localhost/testNode", "root", "root");
for (Vertex v : graph.getVerticesOfClass("Node"))
{
String id = v.getProperty("ID");
System.out.println("Checking children of: " + id);
String sql = "select from node where PARENT_ID = '"+id+"'";
for (Vertex child : (Iterable<Vertex>) graph.command(
new OCommandSQL(sql))
.execute())
{
v.addEdge("parent_of", child);
System.out.println("\tAdded 'Parent Of' Edge from: " + id + " to " + child.getProperty("ID"));
}
graph.commit();
}
来源:https://stackoverflow.com/questions/30507054/orientdb-create-edge-using-kind-of-self-join