您好我有一個數據庫表,看起來像這樣搜索預定義的單詞
word_id int(10)
word varchar(30)
而且我有一個文本,我想看看它在這個文本的話一個在表中定義,什麼是文本這樣做的最優雅的方式?
目前我查詢數據庫中的所有單詞,然後使用PHP搜索整個文本中的每個單詞,所以PHP需要很長時間才能從數據庫中下載所有單詞,然後檢查每個人和每個人他們對我的文本。
您好我有一個數據庫表,看起來像這樣搜索預定義的單詞
word_id int(10)
word varchar(30)
而且我有一個文本,我想看看它在這個文本的話一個在表中定義,什麼是文本這樣做的最優雅的方式?
目前我查詢數據庫中的所有單詞,然後使用PHP搜索整個文本中的每個單詞,所以PHP需要很長時間才能從數據庫中下載所有單詞,然後檢查每個人和每個人他們對我的文本。
你可以嘗試提取文本的話,把他們在這樣一個SELECT查詢:
$words = array_unique(get_words_in_text(...));
$sql = "SELECT * FROM words WHERE word IN (".implode(", ", $words)).")";
可能是你的SQL引擎優化這一說法。在任何情況下,數據庫連接的使用量都小於當前的方法。
您還可以嘗試臨時創建一個單獨的詞表並將文本中的所有單詞添加到該表中。然後你可以用主詞表執行JOIN
。如果兩個表都正確索引,這可能是相當快。
編輯:這個問題/答案表明創建臨時表確實更快(見評論):mysql select .. where .. in -> optimizing。但是,它肯定取決於您使用的具體數據庫,單詞表的大小,文本的大小以及索引的配置。因此,我建議您針對您的特定場景評估這兩種方法。請報告你的結果。 :-)
一個想法:
// get words in file into array
$file = file_get_contents('file.txt', FILE_IGNORE_NEW_LINES);
$file_words = explode(" ", $file);
// remove duplicate words, count elements in array after de-duplication
$file_words = array_unique($file_words);
$file_count = count($file_words);
// create empty array in which to store hits
$words_with_definition = array();
// check to see if each word exists in database
for ($i=0; $i < $file_count; $i++)
{
// intentionally leaving out db connection, this is just a concept
// word should be at least three characters, change as needed
if (strlen($file_words[$i]) >= 3)
{
$sql = "SELECT word FROM your_table WHERE word='".$file_words[$i]."'";
if (mysql_num_rows($sql) > 0)
{
// this is a hit, add it to $words_with_definition
array_push($words_with_definition, $file_words[$i]);
}
}
}
無論是$ words_with_definition陣列將是打了折的數據庫的話。
你有沒有考慮過將文本分割成單詞並在每個單詞中搜索數據庫(顛倒你目前的方法)?它會更有效率。 – JohnFx
如何使用現有的搜索引擎?有幾個開源選項。您可以修改代碼來查詢您的數據庫。 – Dan
不管你做什麼,都要小心這個問題。 (http://thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx) – JohnFx