模式索引与模式约束

package com.fly.demo;

import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.io.fs.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


/**
 * 模式索引(自动索引),允许属性有重复值
 * 模式约束
 */
public class Index {
    public static void main(String... args) throws IOException {
        File dbPath = new File("demo/neo4j.db");
        FileUtils.deleteRecursively(dbPath);

        GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);
        registerShutdownHook(graphDb);

        createIndex(graphDb);
        createUser(graphDb);
        updateUser(graphDb, 0);
        updateUser(graphDb, 1);
        updateUser(graphDb, 2);
        findUser(graphDb);
        deleteUser(graphDb);
        dropIndex(graphDb);

        graphDb.shutdown();
    }

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

    /**
     * 创建User节点
     */
    private static void createUser(GraphDatabaseService graphDb) {
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            for (int id = 0; id < 3; id++) {
                Node node = graphDb.createNode(label);
                node.setProperty("name", "user" + id);
                System.out.println("Create user id=[" + node.getId() + "] name=[" + node.getProperty("name") + "]");
            }
            tx.success();
        }
    }

    private static void findUser(GraphDatabaseService graphDb) {
        Label label = Label.label("User");
        try (
                Transaction tx = graphDb.beginTx();
                ResourceIterator<Node> users = graphDb.findNodes(label)
        ) {
            while (users.hasNext()) {
                Node node = users.next();
                System.out.println("find user is " + node.getProperty("name"));
            }
        }
    }

    private static void deleteUser(GraphDatabaseService graphDb) {
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            for (Node node : loop(graphDb.findNodes(label))) {
                System.out.println("delete user is " + node.getProperty("name"));
                node.delete();
            }
            tx.success();
        }
    }

    /**
     * 修改User节点属性
     */
    private static void updateUser(GraphDatabaseService graphDb, int id) {
        StringBuilder outstr = new StringBuilder();
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            String nameToFind = "user" + id;
            for (Node node : loop(graphDb.findNodes(label, "name", nameToFind))) {
                // 将属性中的数字加1
                // 模式约束会修改索引报错
                node.setProperty("name", "user" + (id + 1));
                outstr.append("Update user name from [").append(nameToFind).append("] to [").append(node.getProperty("name")).append("]");
            }
            tx.success();
        } catch (Exception e) {
            outstr = new StringBuilder("Update error: " + e.getMessage());
        }
        System.out.println(outstr);
    }

    private static ArrayList<Node> loop(ResourceIterator<Node> users) {
        ArrayList<Node> userNodes = new ArrayList<>();
        while (users.hasNext()) {
            userNodes.add(users.next());
        }
        return userNodes;
    }

    private static void createIndex(GraphDatabaseService graphDb) {
        try (Transaction tx = graphDb.beginTx()) {
            // 数据库模式
            Schema schema = graphDb.schema();
            // 在标签为User的节点中为属性name创建模式索引
            schema.indexFor(Label.label("User")).on("name").create();
            // 创建模式约束(将同时创建一个模式索引),并指定唯一属性
//            schema.constraintFor(Label.label("User")).assertPropertyIsUnique("name").create();
            tx.success();
        }
        System.out.println("Create unique index");
    }

    private static void dropIndex(GraphDatabaseService graphDb) {
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            // 删除索引
            for (IndexDefinition indexDefinition : graphDb.schema().getIndexes(label)) {
                indexDefinition.drop();
            }
            // 删除约束
//            for (ConstraintDefinition constraintDefinition : graphDb.schema().getConstraints(label)) {
//                constraintDefinition.drop();
//            }
            tx.success();
        }
        System.out.println("Drop index success.");
    }
}

posted @ 2022-03-28 15:49  fly_bk  阅读(31)  评论(0编辑  收藏  举报