Friday, August 17, 2012

How to CREATE INDEX

Like I said in the last post. BDB does not support indexes in the style of CREATE INDEX. You have to do them all manually. So if we want have our documents database primary key be an auto-incrementing long and also be able to search by document key, then we need to perform the secondary index ourselves.

We do this by creating another section in the documents.db data file.  This is a simple tree that maps the secondary key (our document name) to the primary key (our auto-incrementing long).

this.indexByKeyFile = env.CreateDatabase(DbCreateFlags.None);
this.indexByKey = (DbBTree)indexByKeyFile.Open(null, "documents.db", "indexByKey", DbType.BTree, Db.OpenFlags.Create
 | Db.OpenFlags.ThreadSafe | Db.OpenFlags.AutoCommit, 0);
dataTable.Associate(indexByKey, GetDocumentKeyForIndexByKey, DbFile.AssociateFlags.Create);

The same flags apply as the primary key btree, the difference is the associate call.  This call tells BDB that this section is a secondary index, and that anytime we do a put operation on the primary we want to get informed.  The callback for the event is GetDocumentKeyForIndexByKey and it's job is to pull the secondary key from the primary key's data section (we'll get to the code for that later since we can't write it without the primary table's data structure in place).

Of course, running this server again with a BDB dump, will get us a little closer.

VERSION=3
format=bytevalue
database=data
type=btree
db_pagesize=8192
HEADER=END
DATA=END
VERSION=3
format=bytevalue
database=indexByKey
type=btree
db_pagesize=8192
HEADER=END
DATA=END

We now have two sections of data in the file: the primary data section and the secondary index called indexByKey.

No comments:

Post a Comment