2009-09-03 92 views
0

我已经设置了一个挑战,即创建一个索引器,该索引器将所有单词替换为4个或更多字符,并将它们与单词的使用次数一起存储在数据库中。使用PHP索引文本文件

我必须在4000个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; 
} 

我认为目前最大的瓶颈是存储在数据库中的单词的脚本。它需要将文件添加到散文表,然后如果表中存在的单词只是在字段中附加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"); 
     } 
    } 
} 

回答

1

您可能会考虑分析您的应用,以确切知道瓶颈在哪里。这可能会让您更好地了解可以改进的内容。

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

+0

谢谢n1313!我努力减少查询数据库的次数。谢谢你的帮助。 – Matt 2010-01-08 12:25:28