Search in sources :

Example 16 with Schema

use of org.neo4j.graphdb.schema.Schema in project neo4j by neo4j.

the class FulltextIndexProviderTest method indexWithUnknownAnalyzerWillBeMarkedAsFailedOnStartup.

@Test
void indexWithUnknownAnalyzerWillBeMarkedAsFailedOnStartup() throws Exception {
    // Create a full-text index.
    long indexId;
    try (KernelTransactionImplementation transaction = getKernelTransaction()) {
        int[] propertyIds = { propIdHa };
        SchemaDescriptor schema = SchemaDescriptor.fulltext(EntityType.NODE, new int[] { labelIdHa }, propertyIds);
        IndexPrototype prototype = IndexPrototype.forSchema(schema).withIndexType(FULLTEXT).withName(NAME);
        SchemaWrite schemaWrite = transaction.schemaWrite();
        IndexDescriptor index = schemaWrite.indexCreate(prototype);
        indexId = index.getId();
        transaction.success();
    }
    // Modify the full-text index such that it has an analyzer configured that does not exist.
    controller.restartDbms(builder -> {
        var cacheTracer = NULL;
        FileSystemAbstraction fs = builder.getFileSystem();
        DatabaseLayout databaseLayout = Neo4jLayout.of(builder.getHomeDirectory()).databaseLayout(DEFAULT_DATABASE_NAME);
        DefaultIdGeneratorFactory idGenFactory = new DefaultIdGeneratorFactory(fs, RecoveryCleanupWorkCollector.ignore(), databaseLayout.getDatabaseName());
        try (JobScheduler scheduler = JobSchedulerFactory.createInitialisedScheduler();
            PageCache pageCache = StandalonePageCacheFactory.createPageCache(fs, scheduler, cacheTracer)) {
            StoreFactory factory = new StoreFactory(databaseLayout, Config.defaults(), idGenFactory, pageCache, fs, NullLogProvider.getInstance(), cacheTracer, writable());
            var cursorContext = CursorContext.NULL;
            try (NeoStores neoStores = factory.openAllNeoStores(false)) {
                TokenHolders tokens = StoreTokens.readOnlyTokenHolders(neoStores, CursorContext.NULL);
                SchemaStore schemaStore = neoStores.getSchemaStore();
                SchemaStorage storage = new SchemaStorage(schemaStore, tokens, () -> KernelVersion.LATEST);
                IndexDescriptor index = (IndexDescriptor) storage.loadSingleSchemaRule(indexId, CursorContext.NULL);
                Map<String, Value> indexConfigMap = new HashMap<>(index.getIndexConfig().asMap());
                for (Map.Entry<String, Value> entry : indexConfigMap.entrySet()) {
                    if (entry.getKey().contains("analyzer")) {
                        // This analyzer does not exist!
                        entry.setValue(Values.stringValue("bla-bla-lyzer"));
                    }
                }
                index = index.withIndexConfig(IndexConfig.with(indexConfigMap));
                storage.writeSchemaRule(index, cursorContext, INSTANCE);
                schemaStore.flush(cursorContext);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return builder;
    });
    // Verify that the index comes up in a failed state.
    try (Transaction tx = db.beginTx()) {
        IndexDefinition index = tx.schema().getIndexByName(NAME);
        Schema.IndexState indexState = tx.schema().getIndexState(index);
        assertThat(indexState).isEqualTo(Schema.IndexState.FAILED);
        String indexFailure = tx.schema().getIndexFailure(index);
        assertThat(indexFailure).contains("bla-bla-lyzer");
    }
    // Verify that the failed index can be dropped.
    try (Transaction tx = db.beginTx()) {
        tx.schema().getIndexByName(NAME).drop();
        assertThrows(IllegalArgumentException.class, () -> tx.schema().getIndexByName(NAME));
        tx.commit();
    }
    try (Transaction tx = db.beginTx()) {
        assertThrows(IllegalArgumentException.class, () -> tx.schema().getIndexByName(NAME));
    }
    controller.restartDbms();
    try (Transaction tx = db.beginTx()) {
        assertThrows(IllegalArgumentException.class, () -> tx.schema().getIndexByName(NAME));
    }
}
Also used : FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) HashMap(java.util.HashMap) Schema(org.neo4j.graphdb.schema.Schema) IndexPrototype(org.neo4j.internal.schema.IndexPrototype) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) StoreFactory(org.neo4j.kernel.impl.store.StoreFactory) SchemaStorage(org.neo4j.internal.recordstorage.SchemaStorage) IndexDefinition(org.neo4j.graphdb.schema.IndexDefinition) KernelTransactionImplementation(org.neo4j.kernel.impl.api.KernelTransactionImplementation) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) TokenHolders(org.neo4j.token.TokenHolders) PageCache(org.neo4j.io.pagecache.PageCache) JobScheduler(org.neo4j.scheduler.JobScheduler) SchemaDescriptor(org.neo4j.internal.schema.SchemaDescriptor) SchemaWrite(org.neo4j.internal.kernel.api.SchemaWrite) SchemaStore(org.neo4j.kernel.impl.store.SchemaStore) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) IndexNotApplicableKernelException(org.neo4j.internal.kernel.api.exceptions.schema.IndexNotApplicableKernelException) KernelException(org.neo4j.exceptions.KernelException) TransactionFailureException(org.neo4j.internal.kernel.api.exceptions.TransactionFailureException) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) Transaction(org.neo4j.graphdb.Transaction) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) NeoStores(org.neo4j.kernel.impl.store.NeoStores) Value(org.neo4j.values.storable.Value) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test)

Example 17 with Schema

use of org.neo4j.graphdb.schema.Schema in project neo4j by neo4j.

the class ShutdownOnIndexUpdateIT method createConstraint.

private static void createConstraint(GraphDatabaseService database) {
    try (Transaction transaction = database.beginTx()) {
        Schema schema = transaction.schema();
        schema.constraintFor(CONSTRAINT_INDEX_LABEL).assertPropertyIsUnique(UNIQUE_PROPERTY_NAME).create();
        transaction.commit();
    }
}
Also used : Transaction(org.neo4j.graphdb.Transaction) Schema(org.neo4j.graphdb.schema.Schema)

Example 18 with Schema

use of org.neo4j.graphdb.schema.Schema in project neo4j by neo4j.

the class SchemaAcceptanceTest method shouldThrowConstraintViolationIfAskedToCreateCompoundConstraint.

@Test
void shouldThrowConstraintViolationIfAskedToCreateCompoundConstraint() {
    // WHEN
    UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> {
        try (Transaction tx = db.beginTx()) {
            Schema schema = tx.schema();
            schema.constraintFor(label).assertPropertyIsUnique("my_property_key").assertPropertyIsUnique("other_property").create();
            tx.commit();
        }
    });
    assertThat(e).hasMessageContaining("can only create one unique constraint");
}
Also used : Schema(org.neo4j.graphdb.schema.Schema) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 19 with Schema

use of org.neo4j.graphdb.schema.Schema in project neo4j-documentation by neo4j.

the class EmbeddedNeo4jWithIndexing method main.

public static void main(final String[] args) throws IOException {
    System.out.println("Starting database ...");
    FileUtils.deleteDirectory(databaseDirectory);
    // tag::startDb[]
    DatabaseManagementService managementService = new DatabaseManagementServiceBuilder(databaseDirectory).build();
    GraphDatabaseService graphDb = managementService.database(DEFAULT_DATABASE_NAME);
    // end::startDb[]
    {
        // tag::createIndex[]
        IndexDefinition usernamesIndex;
        try (Transaction tx = graphDb.beginTx()) {
            Schema schema = tx.schema();
            usernamesIndex = // <1>
            schema.indexFor(Label.label("User")).on(// <2>
            "username").withName(// <3>
            "usernames").create();
            // <5>
            tx.commit();
        }
        // tag::wait[]
        try (Transaction tx = graphDb.beginTx()) {
            Schema schema = tx.schema();
            schema.awaitIndexOnline(usernamesIndex, 10, TimeUnit.SECONDS);
        }
        // tag::progress[]
        try (Transaction tx = graphDb.beginTx()) {
            Schema schema = tx.schema();
            System.out.println(String.format("Percent complete: %1.0f%%", schema.getIndexPopulationProgress(usernamesIndex).getCompletedPercentage()));
        }
    // end::progress[]
    }
    {
        // tag::addUsers[]
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            // Create some users
            for (int id = 0; id < 100; id++) {
                Node userNode = tx.createNode(label);
                userNode.setProperty("username", "user" + id + "@neo4j.org");
            }
            System.out.println("Users created");
            tx.commit();
        }
    // end::addUsers[]
    }
    {
        // tag::findUsers[]
        Label label = Label.label("User");
        int idToFind = 45;
        String nameToFind = "user" + idToFind + "@neo4j.org";
        try (Transaction tx = graphDb.beginTx()) {
            try (ResourceIterator<Node> users = tx.findNodes(label, "username", nameToFind)) {
                ArrayList<Node> userNodes = new ArrayList<>();
                while (users.hasNext()) {
                    userNodes.add(users.next());
                }
                for (Node node : userNodes) {
                    System.out.println("The username of user " + idToFind + " is " + node.getProperty("username"));
                }
            }
        }
    // end::findUsers[]
    }
    {
        // tag::resourceIterator[]
        Label label = Label.label("User");
        int idToFind = 45;
        String nameToFind = "user" + idToFind + "@neo4j.org";
        try (Transaction tx = graphDb.beginTx();
            ResourceIterator<Node> users = tx.findNodes(label, "username", nameToFind)) {
            Node firstUserNode;
            if (users.hasNext()) {
                firstUserNode = users.next();
            }
            users.close();
        // ... Do stuff with the firstUserNode we found ...
        }
    // end::resourceIterator[]
    }
    {
        // tag::updateUsers[]
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            int idToFind = 45;
            String nameToFind = "user" + idToFind + "@neo4j.org";
            for (Node node : loop(tx.findNodes(label, "username", nameToFind))) {
                node.setProperty("username", "user" + (idToFind + 1) + "@neo4j.org");
            }
            tx.commit();
        }
    // end::updateUsers[]
    }
    {
        // tag::deleteUsers[]
        try (Transaction tx = graphDb.beginTx()) {
            Label label = Label.label("User");
            int idToFind = 46;
            String nameToFind = "user" + idToFind + "@neo4j.org";
            for (Node node : loop(tx.findNodes(label, "username", nameToFind))) {
                node.delete();
            }
            tx.commit();
        }
    // end::deleteUsers[]
    }
    {
        // tag::dropIndex[]
        try (Transaction tx = graphDb.beginTx()) {
            // <1>
            IndexDefinition usernamesIndex = tx.schema().getIndexByName("usernames");
            usernamesIndex.drop();
            tx.commit();
        }
    // end::dropIndex[]
    }
    System.out.println("Shutting down database ...");
    // tag::shutdownDb[]
    managementService.shutdown();
// end::shutdownDb[]
}
Also used : GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) IndexDefinition(org.neo4j.graphdb.schema.IndexDefinition) Transaction(org.neo4j.graphdb.Transaction) Schema(org.neo4j.graphdb.schema.Schema) Node(org.neo4j.graphdb.Node) DatabaseManagementServiceBuilder(org.neo4j.dbms.api.DatabaseManagementServiceBuilder) Label(org.neo4j.graphdb.Label) ArrayList(java.util.ArrayList) ResourceIterator(org.neo4j.graphdb.ResourceIterator) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService)

Aggregations

Schema (org.neo4j.graphdb.schema.Schema)19 IndexDefinition (org.neo4j.graphdb.schema.IndexDefinition)10 Transaction (org.neo4j.graphdb.Transaction)9 ConstraintDefinition (org.neo4j.graphdb.schema.ConstraintDefinition)5 ArrayList (java.util.ArrayList)4 GraphDatabaseService (org.neo4j.graphdb.GraphDatabaseService)4 Label (org.neo4j.graphdb.Label)4 AssertSchemaResult (apoc.result.AssertSchemaResult)3 Test (org.junit.Test)3 Test (org.junit.jupiter.api.Test)3 Node (org.neo4j.graphdb.Node)3 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 ResourceIterator (org.neo4j.graphdb.ResourceIterator)2 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)2 ConstraintRelationshipInfo (apoc.result.ConstraintRelationshipInfo)1 IndexConstraintNodeInfo (apoc.result.IndexConstraintNodeInfo)1 VirtualNode (apoc.result.VirtualNode)1 File (java.io.File)1 java.util (java.util)1