我被设置了一个挑战,创建一个索引器,接受所有4个字符或更多的单词,并将它们存储在数据库中,以及单词被使用的次数。
我必须在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;
}我认为目前最大的瓶颈是在数据库中存储单词的脚本。它需要将文档添加到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");
}
}
}发布于 2009-09-03 09:09:02
您可以考虑分析您的应用程序,以确切地了解您的瓶颈所在。这可能会让您更好地了解哪些方面可以改进。
关于数据库优化:检查是否在word列上有索引,然后尝试降低访问数据库的次数。也许是INSERT ... ON DUPLICATE KEY UPDATE ...?
https://stackoverflow.com/questions/1372286
复制相似问题