Search in sources :

Example 31 with KernelTransactionImplementation

use of org.neo4j.kernel.impl.api.KernelTransactionImplementation in project neo4j by neo4j.

the class FulltextIndexProviderTest method createIndex.

private IndexDescriptor createIndex(int[] entityTokens, int[] propertyIds, String analyzer, EntityType entityType, boolean eventuallyConsistent) throws KernelException {
    IndexDescriptor fulltext;
    try (KernelTransactionImplementation transaction = getKernelTransaction()) {
        SchemaDescriptor schema = SchemaDescriptor.fulltext(entityType, entityTokens, propertyIds);
        IndexConfig config = IndexConfig.with(FulltextIndexSettingsKeys.ANALYZER, Values.stringValue(analyzer)).withIfAbsent(FulltextIndexSettingsKeys.EVENTUALLY_CONSISTENT, Values.of(eventuallyConsistent));
        IndexPrototype prototype = IndexPrototype.forSchema(schema, DESCRIPTOR).withIndexType(IndexType.FULLTEXT).withName(NAME).withIndexConfig(config);
        fulltext = transaction.schemaWrite().indexCreate(prototype);
        transaction.success();
    }
    return fulltext;
}
Also used : SchemaDescriptor(org.neo4j.internal.schema.SchemaDescriptor) IndexConfig(org.neo4j.internal.schema.IndexConfig) KernelTransactionImplementation(org.neo4j.kernel.impl.api.KernelTransactionImplementation) IndexPrototype(org.neo4j.internal.schema.IndexPrototype) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor)

Example 32 with KernelTransactionImplementation

use of org.neo4j.kernel.impl.api.KernelTransactionImplementation 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 33 with KernelTransactionImplementation

use of org.neo4j.kernel.impl.api.KernelTransactionImplementation in project neo4j by neo4j.

the class FulltextIndexProviderTest method queryingWithIndexProgressorMustProvideScore.

@Test
void queryingWithIndexProgressorMustProvideScore() throws Exception {
    long nodeId = createTheThirdNode();
    IndexDescriptor index;
    index = createIndex(new int[] { labelIdHej, labelIdHa, labelIdHe }, new int[] { propIdHej, propIdHa, propIdHe, propIdHo });
    await(index);
    List<String> acceptedEntities = new ArrayList<>();
    try (KernelTransactionImplementation ktx = getKernelTransaction()) {
        NodeValueIndexCursor cursor = new ExtendedNodeValueIndexCursorAdapter() {

            private long nodeReference;

            private IndexProgressor progressor;

            @Override
            public long nodeReference() {
                return nodeReference;
            }

            @Override
            public boolean next() {
                return progressor.next();
            }

            @Override
            public void initialize(IndexDescriptor descriptor, IndexProgressor progressor, PropertyIndexQuery[] query, IndexQueryConstraints constraints, boolean indexIncludesTransactionState) {
                this.progressor = progressor;
            }

            @Override
            public boolean acceptEntity(long reference, float score, Value... values) {
                this.nodeReference = reference;
                assertFalse(Float.isNaN(score), "score should not be NaN");
                assertThat(score).as("score must be positive").isGreaterThan(0.0f);
                acceptedEntities.add("reference = " + reference + ", score = " + score + ", " + Arrays.toString(values));
                return true;
            }
        };
        Read read = ktx.dataRead();
        IndexReadSession indexSession = ktx.dataRead().indexReadSession(index);
        read.nodeIndexSeek(indexSession, cursor, unconstrained(), fulltextSearch("hej:\"villa\""));
        int counter = 0;
        while (cursor.next()) {
            assertThat(cursor.nodeReference()).isEqualTo(nodeId);
            counter++;
        }
        assertThat(counter).isEqualTo(1);
        assertThat(acceptedEntities.size()).isEqualTo(1);
        acceptedEntities.clear();
    }
}
Also used : NodeValueIndexCursor(org.neo4j.internal.kernel.api.NodeValueIndexCursor) ArrayList(java.util.ArrayList) IndexQueryConstraints(org.neo4j.internal.kernel.api.IndexQueryConstraints) ExtendedNodeValueIndexCursorAdapter(org.neo4j.kernel.impl.newapi.ExtendedNodeValueIndexCursorAdapter) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) IndexReadSession(org.neo4j.internal.kernel.api.IndexReadSession) TokenRead(org.neo4j.internal.kernel.api.TokenRead) Read(org.neo4j.internal.kernel.api.Read) KernelTransactionImplementation(org.neo4j.kernel.impl.api.KernelTransactionImplementation) IndexProgressor(org.neo4j.kernel.api.index.IndexProgressor) Value(org.neo4j.values.storable.Value) Test(org.junit.jupiter.api.Test)

Example 34 with KernelTransactionImplementation

use of org.neo4j.kernel.impl.api.KernelTransactionImplementation in project neo4j by neo4j.

the class FulltextIndexProviderTest method verifyThatFulltextIndexIsPresent.

private void verifyThatFulltextIndexIsPresent(IndexDescriptor fulltextIndexDescriptor) throws TransactionFailureException {
    try (KernelTransactionImplementation transaction = getKernelTransaction()) {
        IndexDescriptor descriptor = transaction.schemaRead().indexGetForName(NAME);
        assertEquals(fulltextIndexDescriptor.schema(), descriptor.schema());
        assertEquals(fulltextIndexDescriptor.isUnique(), descriptor.isUnique());
        transaction.success();
    }
}
Also used : KernelTransactionImplementation(org.neo4j.kernel.impl.api.KernelTransactionImplementation) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor)

Example 35 with KernelTransactionImplementation

use of org.neo4j.kernel.impl.api.KernelTransactionImplementation in project neo4j by neo4j.

the class ConstraintIndexCreator method dropUniquenessConstraintIndex.

/**
 * You MUST hold a schema write lock before you call this method.
 */
public void dropUniquenessConstraintIndex(IndexDescriptor index) throws TransactionFailureException {
    try (KernelTransaction transaction = kernelSupplier.get().beginTransaction(Type.IMPLICIT, AUTH_DISABLED)) {
        ((KernelTransactionImplementation) transaction).addIndexDoDropToTxState(index);
        transaction.commit();
    }
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) KernelTransactionImplementation(org.neo4j.kernel.impl.api.KernelTransactionImplementation)

Aggregations

KernelTransactionImplementation (org.neo4j.kernel.impl.api.KernelTransactionImplementation)35 Test (org.junit.jupiter.api.Test)20 ConstraintIndexCreator (org.neo4j.kernel.impl.api.state.ConstraintIndexCreator)13 IndexDescriptor (org.neo4j.internal.schema.IndexDescriptor)12 IndexingService (org.neo4j.kernel.impl.api.index.IndexingService)8 IndexPrototype (org.neo4j.internal.schema.IndexPrototype)7 StorageReader (org.neo4j.storageengine.api.StorageReader)7 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)6 IndexProxy (org.neo4j.kernel.impl.api.index.IndexProxy)6 DbmsRuntimeRepository (org.neo4j.dbms.database.DbmsRuntimeRepository)5 Transaction (org.neo4j.graphdb.Transaction)5 SchemaDescriptor (org.neo4j.internal.schema.SchemaDescriptor)5 TransactionState (org.neo4j.kernel.api.txstate.TransactionState)5 CommandCreationContext (org.neo4j.storageengine.api.CommandCreationContext)5 InOrder (org.mockito.InOrder)4 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)4 Test (org.junit.Test)3 SecurityAuthorizationHandler (org.neo4j.internal.kernel.api.security.SecurityAuthorizationHandler)3 IndexProviderDescriptor (org.neo4j.internal.schema.IndexProviderDescriptor)3 IndexingProvidersService (org.neo4j.kernel.impl.api.index.IndexingProvidersService)3