其他分享
首页 > 其他分享> > 节点属性的手动索引

节点属性的手动索引

作者:互联网

package com.fly.demo;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.index.Index;
import org.neo4j.io.fs.FileUtils;

import java.io.File;
import java.io.IOException;

/**
 * 节点属性 手动索引
 */
public class ManualIndex {
    private static final File DB_PATH = new File("demo/neo4j-db");
    private static final String USERNAME_KEY = "name";
    private static GraphDatabaseService graphDb;
    private static Index<Node> nodeIndex;

    public static void main(String... args) throws IOException {
        FileUtils.deleteRecursively(DB_PATH);
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
        registerShutdownHook();
        try (Transaction tx = graphDb.beginTx()) {
            nodeIndex = graphDb.index().forNodes("nodes");
            for (int id = 0; id < 100; id++) {
                createAndIndexUser(idToUserName(id));
            }
            int idToFind = 45;
            String userName = idToUserName(idToFind);
            Node foundUser = nodeIndex.get(USERNAME_KEY, userName).getSingle();
            System.out.println("The name of user " + idToFind + " is "
                    + foundUser.getProperty(USERNAME_KEY));
            // * 通配符查询所有节点
            for (Node user : nodeIndex.query(USERNAME_KEY, "*")) {
                nodeIndex.remove(user, USERNAME_KEY, user.getProperties(USERNAME_KEY));
                user.delete();
            }
            tx.success();
        }
        shutdown();
    }

    private static Node createAndIndexUser(final String userName) {
        Node node = graphDb.createNode();
        node.setProperty(USERNAME_KEY, userName);
        nodeIndex.add(node, USERNAME_KEY, userName);
        return node;
    }

    private static String idToUserName(final int id) {
        return "user" + id;
    }

    private static void shutdown() {
        graphDb.shutdown();
    }

    private static void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(ManualIndex::shutdown));
    }
}

标签:USERNAME,手动,private,索引,static,KEY,neo4j,import,节点
来源: https://www.cnblogs.com/fly-book/p/16065613.html