'Search MySQL database with a list of keywords
I'm trying to create a basic search engine with 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. This is because the 2nd example query doesn't work well with the "LIKE" MySQL command.
Is there another approach to querying a MySQL with a list of keywords, and not an exact string? 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?
<?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();
?>
Solution 1:[1]
Unfortunately LIKE will not give you the high accuracy you looking for and also it's a bad solution on a big scale.
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 :)
I hope it's helpful
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmed Hassan |
