如何检索图中两个节点之间的所有简单路径,路径按长度排序。 Cypher查询中有一个order by子句,但我无法在嵌入式数据库的java apis中找到类似的东西。
检索路径后是否有方法或我必须自己对它们进行排序?
答案 0 :(得分:0)
Neo4j有一个用于图算法的Java API包,可以完全按照您的要求进行操作。请参阅以下代码段以了解其工作原理。
要获得更多信息,请参阅reference manual和javadocs。下面的代码段是用groovy编写的,可用here as well:
@Grab(group="org.neo4j", module="neo4j-cypher", version="2.1.3")
@Grab(group="org.neo4j", module="neo4j-lucene-index", version="2.1.3")
@Grab(group='org.neo4j', module='neo4j-graph-algo', version='2.1.3')
import org.neo4j.graphdb.factory.GraphDatabaseFactory
import org.neo4j.graphdb.PathExpander
import org.neo4j.graphdb.PathExpanders
import org.neo4j.graphdb.Path
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.Node
import org.neo4j.graphdb.DynamicLabel
import org.neo4j.graphalgo.GraphAlgoFactory
import org.neo4j.graphalgo.PathFinder
import org.neo4j.helpers.collection.IteratorUtil
import org.neo4j.cypher.javacompat.ExecutionEngine
def db = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder("graph.db")
.newGraphDatabase()
def ee = new ExecutionEngine(db)
ee.execute("""
create (a:myLabel {myprop:'a'}),
(b:myLabel {myprop:'b'}),
(c:myLabel {myprop:'c'}),
(d:myLabel {myprop:'d'}),
(a)-[:KNOWS]->(b),
(a)-[:KNOWS]->(c),
(c)-[:KNOWS]->(b),
(c)-[:KNOWS]->(e),
(d)-[:KNOWS]->(b)
""")
def tx = db.beginTx()
try {
// lookup start and end node
Label label = DynamicLabel.label("myLabel")
Node startNode = IteratorUtil.single(db.findNodesByLabelAndProperty(label, "myprop", "a"))
Node endNode = IteratorUtil.single(db.findNodesByLabelAndProperty(label, "myprop", "b"))
PathExpander pathExpander = PathExpanders.allTypesAndDirections() // adopt to your needs
def maxDepth = 5 // adopt to your needs
PathFinder<Path> pathFinder = GraphAlgoFactory.allSimplePaths(pathExpander, maxDepth)
Iterable<Path> result = pathFinder.findAllPaths(startNode, endNode)
// sort the results, in java this is more effort ;-)
List<Path> sortedResult = result.sort { it.length() }
for (Path p: sortedResult) {
println p
}
tx.success()
} finally {
tx.finish()
}
db.shutdown()