2009-09-03 94 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