简体   繁体   English

需要一个PHP MySQL脚本来搜索数据库中的关键字

[英]Need a PHP MySQL script to search for keywords in a database

I need to implement a search option for user comments that are stored in a MySQL database. 我需要为存储在MySQL数据库中的用户注释实现搜索选项。 I would optimally like it to work in a similar manner to a standard web page search engine, but I am trying to avoid the large scale solutions. 我最希望它以与标准网页搜索引擎类似的方式工作,但是我试图避免使用大型解决方案。 I'd like to just get a feel for the queries that would give me decent results. 我只是想了解一下可以给我带来体面的结果的查询。 Any suggestions? 有什么建议么? Thanks. 谢谢。

It's possible to create a full indexing solution with some straightforward steps. 可以通过一些简单的步骤来创建完整的索引解决方案。 You could create a table that maps words to each post, then when you search for some words find all posts that match. 您可以创建一个将单词映射到每个帖子的表,然后在搜索某些单词时找到所有匹配的帖子。

Here's a short algorithm: 这是一个简短的算法:

  1. When a comment is posted, convert the string to lowercase and split it into words (split on spaces, and optionally dashes/punctuation). 发表评论后,将字符串转换为小写并将其拆分为单词(以空格分隔,还可以选择破折号/标点符号)。
  2. In a "words" table store each word with an ID, if it's not already in the table. 在“单词”表中,存储每个单词和一个ID(如果该单词尚未在表中)。 (Here you might wish to ignore common words like 'the' or 'for'.) (在这里,您可能希望忽略常见的单词,例如“ the”或“ for”。)
  3. In an "indexedwords" table map the IDs of the words you just inserted to the post ID of the comment (or article if that is what you want to return). 在“ indexedwords”表中,将您刚插入的单词的ID映射到评论的帖子ID(如果要返回,则为文章的ID)。
  4. When searching, split the search term on words and find all posts that contain each of the words. 搜索时,将搜索词拆分为单词,然后查找包含每个单词的所有帖子。 (Again here you might want to ignore common words.) (再次在这里,您可能要忽略常用词。)
  5. Order the results by number of occurrences. 按出现次数对结果进行排序。 If the results must contain all the words you'd need to find the union of your different arrays of posts. 如果结果必须包含所有单词,则需要找到不同帖子数组的并集。

As an entry point, you can use MySQL LIKE queries. 作为入口,可以使用MySQL LIKE查询。

For example if you have a table 'comments' with a column named 'comment', and you want to find all comments that contain the word 'red', use: 例如,如果您有一个表“ comments”和一个名为“ comment”的列,并且想要查找包含单词“ red”的所有注释,请使用:

SELECT comment FROM comments WHERE comment LIKE '% red %';

Please note that fulltext searches can be slow, so if your database is very large or if you run this query a lot, you will want to find an optimized solution, such as Sphinx (http://sphinxsearch.com). 请注意,全文搜索可能会很慢,因此,如果您的数据库很大,或者您经常运行此查询,则需要找到一种优化的解决方案,例如Sphinx(http://sphinxsearch.com)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM