在Traver中的setProperty之后显示错误的值

时间:2014-01-16 16:42:19

标签: java neo4j

以下是带有两种边缘的neo4j图。首先,我们遍历边(BFS),然后标准化每种边的属性值。但是,当在不同的循环中检索值时,将打印错误的值。

这看起来非常奇怪。可能是我错过了什么。如果有的话,这将是非常有帮助的 一个让我纠正或建议我一个更好的方法来避免这个错误。在此先感谢:)

package org.neo4j.examples;

import java.io.File;
import java.util.HashMap;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.traversal.Evaluator;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.graphdb.traversal.Uniqueness;
import org.neo4j.kernel.Traversal;

public class MyNeo4jExpt {
    public enum RelTypes implements RelationshipType {
        CO_OCCURANCE, CAMPAIGN
    }

    private static final String MY_TRAVERSAL_DB = "target/my-traversal-db";
    private GraphDatabaseService graphDb;

    static Node shop1 = null;
    Node shop2 = null;
    Node shop3 = null;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyNeo4jExpt matrix = new MyNeo4jExpt();
        matrix.setUp();
        matrix.normalizeRelations(shop1);
        matrix.shutdown();
    }

    public void setUp() {
        deleteFileOrDirectory(new File(MY_TRAVERSAL_DB));
        graphDb = new GraphDatabaseFactory()
                .newEmbeddedDatabase(MY_TRAVERSAL_DB);
        registerShutdownHook();
        createNodespace();
    }

    public void shutdown() {
        graphDb.shutdown();
    }

    public void createNodespace() {
        try (Transaction tx = graphDb.beginTx()) {

            // Create shop1
            shop1 = graphDb.createNode();
            shop1.setProperty("name", "FurnitureShop-1");

            // create shop2
            shop2 = graphDb.createNode();
            shop2.setProperty("name", "FurnitureShop-2");

            // create shop3
            shop3 = graphDb.createNode();
            shop3.setProperty("name", "FurnitureShop-3");

            // ////// connect shop1 to shop2 ///////
            Relationship rel = shop1.createRelationshipTo(shop2,
                    RelTypes.CO_OCCURANCE);
            rel.setProperty("coOccurence", (Double) 5.0);

            rel = shop1.createRelationshipTo(shop2, RelTypes.CAMPAIGN);
            rel.setProperty("furniture", (Double) 0.6);
            rel.setProperty("chair", (Double) 0.6);
            rel.setProperty("table", (Double) 0.6);
            // ///////////////////////////////////////

            // ///// connect shop1 to shop3///////
            rel = shop1.createRelationshipTo(shop3, RelTypes.CAMPAIGN);
            rel.setProperty("furniture", (Double) 0.7);
            rel.setProperty("sofa", (Double) 0.7);
            // ////////////////////////////////////////

            // ////// connect shop3 to shop2 ///////
            rel = shop3.createRelationshipTo(shop2, RelTypes.CO_OCCURANCE);
            rel.setProperty("coOccurence", (Double) 4.0);
            // ///////////////////////////////////////

            tx.success();
        }
    }

    // this function calls a BFS on the given node
    // and normalize relation properties w.r.t. the
    // right edge type (RelType)
    private Traverser normalizeRelations(final Node node) {
        Traverser friendsTraverser = null;
        HashMap<Relationship, Path> relHash = new HashMap<Relationship, Path>();
        try (Transaction tx = graphDb.beginTx()) {
            if (node == null) {
                System.out.println("\nNULL NODE\n");
                return null;
            }
            friendsTraverser = getFriends(node);

            if (friendsTraverser == null) {
                System.err.println("NULL TRAVERSER");
                return null;
            }

            HashMap<RelationshipType, Double> maxVal = new HashMap<RelationshipType, Double>();
            String temp = "";
            try (Transaction tx2 = graphDb.beginTx()) {
                for (Path friendPath : friendsTraverser) {
                    System.out.println("\nAt depth " + friendPath.length()
                            + " => " + friendPath.toString());
                    // output += friendPath.startNode().getProperty("name")+ " "
                    // ;
                    for (Relationship rel : friendPath.relationships()) {
                        temp = " " + rel.getStartNode().getProperty("name");
                        for (String name : rel.getPropertyKeys()) {
                            Double propVal = (Double) rel.getProperty(name);
                            temp += "---" + "(" + name + ", " + propVal + ")";
                            if ((maxVal.get(rel.getType()) == null)
                                    || (propVal > maxVal.get(rel.getType()))) {
                                maxVal.put(rel.getType(), propVal); // <----
                                                                    // Save the
                                                                    // Max Value
                                                                    // for
                                                                    // Particular
                                                                    // Rel Type
                            }
                        }

                        temp += "----" + rel.getEndNode().getProperty("name")
                                + "\n";

                    }
                    // numberOfFriends++;
                    System.out.println(temp);
                }
                tx2.success();
            }
            System.out.println("*************************************");
            System.out.println("**** Devide w.r.t maxVal = "
                    + maxVal.entrySet()
                    + "And Normalized Values Are:*************");
            System.out.println("*************************************");
            temp = "";
            for (Path friendPath : friendsTraverser) {
                System.out.println("\nAt depth " + friendPath.length() + " => "
                        + friendPath.toString());
                for (Relationship rel : friendPath.relationships()) {
                    temp = "" + rel.getStartNode().getProperty("name");
                    try (Transaction tx3 = graphDb.beginTx()) {
                        for (String propName : rel.getPropertyKeys()) {
                            Double propVal = (Double) rel.getProperty(propName)
                                    / maxVal.get(rel.getType());
                            rel.setProperty(propName, propVal);
                            temp += "---" + "(" + propName + ", "
                                    + rel.getProperty(propName) + ")";
                        }
                        tx3.success();
                    }
                    temp += "----" + rel.getEndNode().getProperty("name")
                            + "\n";
                }
                System.out.println(temp);
            }
            tx.success();

        }
        System.out
                .println("\n+++++++++++++NOW WRONG VALUES WILL BE PRINTED+++++++++++++++");
        try (Transaction tx = graphDb.beginTx()) {
            String temp = "";
            for (Path friendPath : friendsTraverser) {
                System.out.println("\nAt depth " + friendPath.length() + " => "
                        + friendPath.toString());
                for (Relationship rel : friendPath.relationships()) {
                    temp = " " + rel.getStartNode().getProperty("name");
                    for (String propName : rel.getPropertyKeys()) {
                        temp += "---" + "(" + propName + ", "
                                + rel.getProperty(propName) + ")";
                    }
                    temp += "----" + rel.getEndNode().getProperty("name")
                            + "\n";
                }
                System.out.println(temp);
            }
            tx.success();
        }
        return friendsTraverser;
    }

    // START SNIPPET: get-friends
    private static Traverser getFriends(final Node person) {
        TraversalDescription td = Traversal.description().breadthFirst()
                .relationships(RelTypes.CAMPAIGN, Direction.BOTH)
                .relationships(RelTypes.CO_OCCURANCE, Direction.BOTH)
                .evaluator(Evaluators.toDepth(10))
                .evaluator(Evaluators.excludeStartPosition())
                .uniqueness(Uniqueness.RELATIONSHIP_GLOBAL);
        return td.traverse(person);
    }

    // END SNIPPET: get-friends

    private void registerShutdownHook() {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running example before it's completed)
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                graphDb.shutdown();
            }
        });
    }

    private static void deleteFileOrDirectory(final File file) {
        if (!file.exists()) {
            return;
        }

        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                deleteFileOrDirectory(child);
            }
        } else {
            file.delete();
        }
    }
}
这是// @ /////////////// ////////////////

At depth 1 => (0)--[CAMPAIGN,1]-->(1)
 FurnitureShop-1---(furniture, 0.6)---(chair, 0.6)---(table, 0.6)----FurnitureShop-2


At depth 1 => (0)--[CAMPAIGN,2]-->(2)
 FurnitureShop-1---(furniture, 0.7)---(sofa, 0.7)----FurnitureShop-3


At depth 1 => (0)--[CO_OCCURANCE,0]-->(1)
 FurnitureShop-1---(coOccurence, 5.0)----FurnitureShop-2


At depth 2 => (0)--[CAMPAIGN,1]-->(1)<--[CO_OCCURANCE,3]--(2)
 FurnitureShop-3---(coOccurence, 4.0)----FurnitureShop-2

*************************************
**** Devide w.r.t maxVal = [RelationshipTypeToken[name:CO_OCCURANCE, id:0]=5.0, RelationshipTypeToken[name:CAMPAIGN, id:1]=0.7]And Normalized Values Are:*************
*************************************

At depth 1 => (0)--[CAMPAIGN,1]-->(1)
FurnitureShop-1---**(furniture, 0.8571428571428572)---(chair, 0.8571428571428572)---(table, 0.8571428571428572)**----FurnitureShop-2


At depth 1 => (0)--[CAMPAIGN,2]-->(2)
FurnitureShop-1---(furniture, 1.0)---(sofa, 1.0)----FurnitureShop-3


At depth 1 => (0)--[CO_OCCURANCE,0]-->(1)
FurnitureShop-1---(coOccurence, 1.0)----FurnitureShop-2


At depth 2 => (0)--[CAMPAIGN,1]-->(1)<--[CO_OCCURANCE,3]--(2)
FurnitureShop-3---(coOccurence, 0.8)----FurnitureShop-2


+++++++++++++NOW **WRONG VALUES** WILL BE PRINTED+++++++++++++++

At depth 1 => (0)--[CAMPAIGN,1]-->(1)
 FurnitureShop-1---**(furniture, 1.2244897959183676)---(chair, 1.2244897959183676)**---(table, 1.2244897959183676)----FurnitureShop-2


At depth 1 => (0)--[CAMPAIGN,2]-->(2)
 FurnitureShop-1---(furniture, 1.0)---(sofa, 1.0)----FurnitureShop-3


At depth 1 => (0)--[CO_OCCURANCE,0]-->(1)
 FurnitureShop-1---(coOccurence, 1.0)----FurnitureShop-2


At depth 2 => (0)--[CAMPAIGN,1]-->(1)<--[CO_OCCURANCE,3]--(2)
 FurnitureShop-3---(coOccurence, 0.8)----FurnitureShop-2

1 个答案:

答案 0 :(得分:1)

  1. 尝试删除内部交易,但它们对您没有帮助,
  2. 设置或打印出值时,还会打印出节点和相关内容的id,以便您看到实际上正在查看相同的对象