简体   繁体   English

使用关键字列表搜索 MySQL 数据库

[英]Search MySQL database with a list of keywords

I'm trying to create a basic search engine with MySQL.我正在尝试使用 MySQL 创建一个基本的搜索引擎。

For example, I have a database of news articles related to Obama.例如,我有一个与奥巴马相关的新闻文章数据库。

When a user inputs the query "Obama", my current approach returns a bunch of articles, but if the query is "Obama news", then it returns 0 results.当用户输入查询“Obama”时,我目前的方法返回一堆文章,但如果查询是“Obama news”,则返回 0 个结果。 This is because the 2nd example query doesn't work well with the "LIKE" MySQL command.这是因为第二个示例查询不能很好地与“LIKE”MySQL 命令一起使用。

Is there another approach to querying a MySQL with a list of keywords, and not an exact string?是否有另一种方法可以使用关键字列表而不是确切的字符串来查询 MySQL? For example, could I search the database with the keywords "obama" and "news" which would return many results instead of "obama news" which returns 0 results?例如,我可以使用关键字“obama”和“news”搜索数据库,这样会返回很多结果,而不是使用“obama news”返回 0 个结果吗?

<?php

$servername = "localhost";
$username = "root";
$password = "";

try {

    $dataConnection = new PDO("mysql:host=$servername;dbname=content", $username, $password);
    $dataConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    //echo "Connection failed: " . $e->getMessage();
    }

$query = "obama news"; // Returns no results
$query = "obama"; // Returns many results

$sql_query = $dataConnection->prepare("SELECT *
FROM newssites WHERE name LIKE :query
OR snippet LIKE :query
LIMIT 10");
$searchQuery = "%". $query ."%";
$sql_query->bindParam(":query", $searchQuery);
$sql_query->execute();

$result = $sql_query->fetchAll(); 

?>

Unfortunately LIKE will not give you the high accuracy you looking for and also it's a bad solution on a big scale.不幸的是, LIKE不会给你你想要的高精度,而且它在大规模上也是一个糟糕的解决方案。

you can build a keywords or tags table and index all articles that are related and the query will be something like this你可以建立一个关键字或标签表并索引所有相关的文章,查询将是这样的

SELECT * FROM `articles`
INNER JOIN keywords_articles as ta ON ka.article_id = articles.id
INNER JOIN keywords AS k ON k.id = ka.keyword_id
WHERE ka.keyword_id = $yourKeywordId;

the last solution is not related to MySQL but its amazing to scale this to use elasticsearch and create your full-text search service for your article:)最后一个解决方案与 MySQL 无关,但将其扩展为使用 elasticsearch 并为您的文章创建全文搜索服务真是太棒了:)

I hope it's helpful希望对您有所帮助

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

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