Skip to content

Indexing

Fast ACID NoSQL Application Database edited this page Sep 22, 2019 · 4 revisions

on DB4O set Index on Field, not Property.

package com.db4odoc.performance;
import com.db4o.config.annotations.Indexed;
import org.joda.time.DateTime;
import java.util.Date;

public class Item {
    @Indexed
    private final String indexedString;
    @Indexed
    private final int indexNumber;
    @Indexed
    private final Date indexDate;

    public Item(int number) {
        this.indexedString = dataString(number);
        this.indexNumber = number;
        DateTime dt = new DateTime(number);
        this.indexDate = dt.toDate();
    }

    public String getIndexedString() {
        return indexedString;
    }

    public static String dataString(int number){
        return "data for "+number;
    }

    public boolean complexMethod(){
        return indexedString.split("for")[0].contains("5");
    }

    public int getIndexNumber() {
        return indexNumber;
    }

    public Date getIndexDate() {
        return indexDate;
    }
}
//use final to value;
final String criteria = Item.dataString(rnd.nextInt(NUMBER_OF_ITEMS));
final List<Item> result = container.query(new Predicate<Item>() {
   @Override
   public boolean match(Item o) {
     return o.getIndexedString().equals(criteria);
   }
});
//dotn't Computing expression in query
//return o.getIndexedString().equals("data for " + number);

Diagnostic

package com.db4odoc.indexing.check;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.ext.StoredClass;
import com.db4o.ext.StoredField;


public class CheckForAndIndex {
    public static void main(String[] args) {

        EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
        configuration.common().objectClass(IndexedClass.class).objectField("id").indexed(true);
        ObjectContainer container = Db4oEmbedded.openFile(configuration, "database.db4o");
        try {
            container.store(new IndexedClass(1));

            // #example: Check for a index
            StoredClass metaInfo = container.ext().storedClass(IndexedClass.class);
            // list a fields and check if they have a index
            for (StoredField field : metaInfo.getStoredFields()) {
                if(field.hasIndex()){
                    System.out.println("The field '"+field.getName()+"' is indexed");
                } else{
                    System.out.println("The field '"+field.getName()+"' isn't indexed");
                }
            }
            // #end example
        } finally {
            container.close();
        }
    }

    static class IndexedClass {
        private int id;
        private String data;

        public IndexedClass(int id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }
    }

}
   private static ObjectContainer openDatabase() {
        // #example: Filter for unindexed fields
        EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
        configuration.common().diagnostic()
                .addListener(new DiagnosticFilter(new DiagnosticToConsole(), LoadedFromClassIndex.class));
        // #end example
        return Db4oEmbedded.openFile(configuration, DATABASE_FILE_NAME);
    }

    // #example: A simple message filter
    private static class DiagnosticFilter implements DiagnosticListener{
        private final Set<Class> filterFor;
        private final DiagnosticListener delegate;

        private DiagnosticFilter(DiagnosticListener delegate,Class<? extends Diagnostic>...filterFor) {
            this.delegate = delegate;
            this.filterFor = new HashSet<Class>(Arrays.asList(filterFor));
        }

        public void onDiagnostic(Diagnostic diagnostic) {
            Class<?> type = diagnostic.getClass();
            if(filterFor.contains(type)){
                delegate.onDiagnostic(diagnostic);
            }
        }
    }
    // #end example

Unique Index

package com.db4odoc.features.uniqueconstrain;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.constraints.UniqueFieldValueConstraint;
import com.db4o.constraints.UniqueFieldValueConstraintViolationException;


public class UniqueConstrainExample {

    public static void main(String[] args) {
        uniqueConstrainOnEmbedded();
    }

    private static void uniqueConstrainOnEmbedded() {
        EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
        // #example: Add the index the field and then the unique constrain
        config.common().objectClass(UniqueId.class).objectField("id").indexed(true);
        config.common().add(new UniqueFieldValueConstraint(UniqueId.class, "id"));
        // #end example
        ObjectContainer container = Db4oEmbedded.openFile(config, "database.db4o");
        try {
            container.store(new UniqueId(44));
            // #example: Violating the constrain throws an exception
            container.store(new UniqueId(42));
            container.store(new UniqueId(42));
            try {
                container.commit();
            } catch (UniqueFieldValueConstraintViolationException e) {
                e.printStackTrace();
            }
            // #end example
        } finally {
            container.close();
        }
    }


    private static class UniqueId {
        private final int id;

        private UniqueId(int id) {
            this.id = id;
        }
    }
}

Unique Constraints

Unique constraints allow a user to define a field to be unique across all the objects of a particular class stored to db4o. This means that you cannot save an object where a previously committed object has the same field value for fields marked as unique. A Unique Constraint is checked at commit-time and a constraint violation will cause a UniqueFieldValueConstraintViolationException to be thrown. This functionality is based on Commit-Time Callbacks feature.

How To Use Unique Constraints

First you need to add an index on the field which should be unique. After that you add the UniqueFieldValueConstraint to the configuration for the unique field.

After that, the unique constrain is applied. When you commit a transaction the uniqueness of the field is checked. If there's any violation, the UniqueFieldValueConstraintViolationException will be thrown.

Client-Server

In client server mode you need to configure the unique constrains on the server side.

Messages-Types

Every diagnostic message is represented by it's own type. You can filter the messages by checking for certain instances. Take a look how you can filter for certain messages.

MissingClass: Notifies you that a class couldn't be found. You should add that class in order to avoid problems. If you've renamed the class, you should rename it in the database or add an alias.

DefragmentRecommendation: Notifies you that you should consider to defragment the database.

LoadedFromClassIndex: Notifies you that db4o couldn't use a field-index to perform a query. This means that the query runs extremely slow on larger data sets. Consider adding a field-index.

DescendIntoTranslator: Means that you a query couldn't be optimized, because the query touches a class with a translator. Therefore the query runs slow. You should consider working without a translator or changing the query.

ClassHasNoFields: You stored a class which has no fields. Even when the class has no fields it need to maintain its class index and needs to be stored. So it adds overhead for storing 'empty' objects. You should consider removing the empty class.

DeletionFailed: db4o failed to delete a object from the database.

UpdateDepthGreaterOne: You have configured a update depth greater one. A large update depth slows down updates significantly. Consider reducing the update-depth and use another strategies to update objects correctly, like transparent persistence.

NativeQueryNotOptimized: A native query couldn't be optimized. An unoptimized query runs significantly slower than a optimized query. Consider to simplify you're query.

NativeQueryOptimizerNotLoaded: Couldn't load the native query optimizer. Ensure that all required are added to your application.

NotTransparentActivationEnabled: Notifies you when a class doesn't support transparent activation. Such object need to be fully activated and slow down the activation process.

ObjectFieldDoesNotExist: A query uses a object-field which doesn't exist. Check you're queries to use only exising fields.

Clone this wiki locally