Neo4J TraversalDescription Definition

不打扰是莪最后的温柔 提交于 2019-12-23 03:51:27

问题


I am trying to create a TraversalDescription that will perform the following search;

  • Return only nodes that have a certain property ("type" == "PERSON")
  • Return a certain fixed number of results (the entire graph is huge, we are only interested in the local graph)
  • Any relationship types can be used

I haven't managed to get very far, I can't seem to figure out how to create an Evaluator for node properties;

TraversalDescription td = Traversal.description().bredthFirst().evaluator(?...);

回答1:


I fixed this by simply implementing the Evaluator interface, and overwriting the Evaluator.evaluate(Path p) method;

public final class MyEvaluator implements Evaluator {

    private int peopleCount;
    private int maxPeople;

    public MyEvaluator(int max) {
        maxPeople = max;
        peopleCount = 0;
    }

    public Evaluation evaluate(Path p) {

        //prune if we have found the required number already
        if(peopleCount >= maxPeople) return Evaluation.EXCLUDE_AND_PRUNE;

        //grab the node of interest
        Node n = p.endNode();

        //include if it is a person
        if(n.hasProperty("type") && (n.getProperty("type").equals(NodeTypes.PERSON.name()))) {
            peopleCount++;
            return Evaluation.INCLUDE_AND_CONTINUE;
        }

        // otherwise just carry on as normal
        return Evaluation.EXCLUDE_AND_CONTINUE;
    }
}

And then my TraversalDescription definition ends up looking like:

TraversalDescription td = Traversal.description().breadthFirst().evaluator(new MyEvaluator(peopleRequired));



回答2:


Even when coding in Java, I'd recommend starting with a Cypher query for traversals, only dropping down into TraversalDescriptions if you really want to tweak the performance or conduct some interesting operations.

From what you've described and assuming you have the id of the start node, a Cypher query could be:

start n=node(1) match (n)-[*1..2]-(m) where m.type="Person" return distinct(m) limit 2

That would find all nodes between 1 and 2 hops away from the starting node, following any relationship type, but where the nodes have a type property set to "Person", finally returning only 2 distinct results. You can try that using an example on console (to which I've added "type" properties).

To execute that from within Java, you'd create an ExecutionEngine, provide the query, then iterate over the results as described in the Neo4j Manual.



来源:https://stackoverflow.com/questions/11633940/neo4j-traversaldescription-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!