Deleting Secondary Database Entries

In general, you can not modify a secondary database directly. In order to modify a secondary database, you should modify the primary database and simply allow JE to manage the secondary modifications for you.

However, as a convenience, you can delete a SecondaryDatabase record directly. Doing so causes the associated primary key/data pair to be deleted. This in turn causes JE to delete all SecondaryDatabase records that reference the primary record.

You can use the SecondaryDatabase.delete() method to delete a secondary database record. Note that if your SecondaryDatabase supports duplicate records, then only the first record in the matching duplicates set is deleted by this method. To delete all the duplicate records that use a given key, use a SecondaryCursor.

Note

SecondaryDatabase.delete() causes the previously describe delete operations to occur only if:

  • the SecondaryKeyCreator.createSecondaryKey() method returns true (see Implementing Key Creators for information on this interface and method).

  • the primary database is opened for write access.

If either of these conditions are not met, then no delete operations can be performed on the secondary database.

For example:

import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryDatabase;

...
// Omitting all database and environment opens
...

try {
    String searchName = "Todd Fulmer";
    DatabaseEntry searchKey = 
        new DatabaseEntry(searchName.getBytes("UTF-8"));

    // Delete the first secondary record that uses "Todd Fulmer" as
    // a key. This causes the primary record referenced by this secondary
    // record to be deleted.
    OperationStatus retVal = mySecondaryDatabase.delete(null, searchKey);
} catch (Exception e) {
    // Exception handling goes here
}