From bafb629b6afb3ad899a53ebb4a976340a1165b1a Mon Sep 17 00:00:00 2001 From: Kacper Donat Date: Fri, 14 Dec 2018 22:32:02 +0100 Subject: [PATCH] optimizing --- index.c | 38 ++++++++++++++++++++++++++++++++++++++ index.h | 2 ++ openidx.c | 8 ++++++++ 3 files changed, 48 insertions(+) diff --git a/index.c b/index.c index e602be7..1a1fa27 100644 --- a/index.c +++ b/index.c @@ -672,3 +672,41 @@ void btree_flush(btree_t* tree) file_flush(tree->file); file_flush(tree->main->file); } + +void _btree_optimize_page(btree_t* tree, tape_t* tmp, page_t page) +{ + if (!page) return; + + btree_node_t node; + btree_entry_t *entry; + record_t record; + _btree_load_node(&node, tree, page); + + for (int i = 0; i < node.header.entries; i++) { + entry = btree_get_entry(&node, i); + _btree_optimize_page(tree, tmp, entry->left); + + tape_read(tree->main, entry->location, &record, sizeof(record_t)); + entry->location = tape_append(tmp, &record, sizeof(record_t)); + } + _btree_write_node(&node, tree, node.page); + + _btree_optimize_page(tree, tmp, entry->right); +} + +void btree_optimize(btree_t *tree) +{ + char tmp[PATH_MAX + 4], old[PATH_MAX]; + strcpy(old, tree->main->file->filename); + sprintf(tmp, "%s.tmp", old); + + tape_t *temp = tape_open(tmp, "wb+"); + _btree_optimize_page(tree, temp, tree->header.root); + tape_close(temp); + tape_close(tree->main); + + remove(old); + rename(tmp, old); + + tree->main = tape_open(old, "rb+"); +} diff --git a/index.h b/index.h index 1ee7fe1..5e61868 100644 --- a/index.h +++ b/index.h @@ -70,6 +70,8 @@ typedef struct { int btree_init(btree_t *tree, char* filename, size_t d); int btree_open(btree_t *tree, char* filename); +void btree_optimize(btree_t *tree); + page_t btree_insert(btree_t *tree, record_t record); page_t btree_remove(btree_t *tree, record_key_t key); bool btree_update(btree_t *tree, record_key_t key, record_t record); diff --git a/openidx.c b/openidx.c index 5514184..2aca95b 100644 --- a/openidx.c +++ b/openidx.c @@ -68,6 +68,7 @@ result_t update_command(const char* command, char* args); result_t verbosity_command(const char* command, char* args); result_t iostat_command(const char* command, char* args); result_t flush_command(const char* command, char* args); +result_t optimize_command(const char* command, char* args); static command_t commands[] = { { "help", "Prints out help", help_command }, @@ -83,6 +84,7 @@ static command_t commands[] = { { "iostat", "Prints IO counts", iostat_command }, { "flush", "Fluhshes index into disk", flush_command }, { "verbosity", "Changes the verbosity", verbosity_command }, + { "optimize", "Optimizes the index", optimize_command }, }; result_t exit_command(const char* command, char* args) @@ -102,6 +104,12 @@ result_t flush_command(const char* command, char* args) return RESULT_OK; } +result_t optimize_command(const char* command, char* args) +{ + btree_optimize(&tree); + return RESULT_OK; +} + result_t verbosity_command(const char* command, char* args) { verbosity_t v;