0

我面临着创建一个索引器的挑战,该索引器将所有单词 4 个或更多字符,并将它们与该单词的使用次数一起存储在数据库中。

我必须在 4,000 个 txt 文件上运行这个索引器。目前,大约需要 12-15 分钟 - 我想知道是否有人对加快速度有建议?

目前我将单词放在一个数组中,如下所示:

// ==============================================================
// === Create an index of all the words in the document
// ==============================================================
function index(){
    $this->index = Array();
    $this->index_frequency = Array();

    $this->original_file = str_replace("\r", " ", $this->original_file);
    $this->index = explode(" ", $this->original_file);

    // Build new frequency array
    foreach($this->index as $key=>$value){
        // remove everything except letters
        $value = clean_string($value);

        if($value == '' || strlen($value) < MIN_CHARS){
            continue;
        }

        if(array_key_exists($value, $this->index_frequency)){
            $this->index_frequency[$value] = $this->index_frequency[$value] + 1;
        } else{
            $this->index_frequency[$value] = 1;
        }
    }
    return $this->index_frequency;
}

我认为目前最大的瓶颈是在数据库中存储单词的脚本。它需要将文档添加到essays表中,然后如果表中存在单词,只需将essayid(单词的频率)附加到字段中,如果单词不存在,则添加它......

// ==============================================================
// === Store the word frequencies in the db
// ==============================================================
private function store(){
    $index = $this->index();

    mysql_query("INSERT INTO essays (checksum, title, total_words) VALUES ('{$this->checksum}', '{$this->original_filename}', '{$this->get_total_words()}')") or die(mysql_error());

    $essay_id = mysql_insert_id();

    foreach($this->index_frequency as $key=>$value){

        $check_word = mysql_result(mysql_query("SELECT COUNT(word) FROM `index` WHERE word = '$key' LIMIT 1"), 0);

        $eid_frequency = $essay_id . "(" . $value . ")";

        if($check_word == 0){
            $save = mysql_query("INSERT INTO `index` (word, essays) VALUES ('$key', '$eid_frequency')");
        } else {
            $eid_frequency = "," . $eid_frequency;
            $save = mysql_query("UPDATE `index` SET essays = CONCAT(essays, '$eid_frequency') WHERE word = '$key' LIMIT 1");
        }
    }
}
4

1 回答 1

1

您可能会考虑分析您的应用程序以准确了解您的瓶颈在哪里。这可能会让您更好地了解可以改进的地方。

关于数据库优化:检查列上是否有索引word,然后尝试降低访问数据库的次数。INSERT ... ON DUPLICATE KEY UPDATE ..., 也许?

于 2009-09-03T09:09:02.260 回答