【发布时间】:2012-06-19 12:27:27
【问题描述】:
我只是从 Sphinx 开始。到目前为止,我成功安装了它,在我的 MySQL 数据库上获得了一个名为 profiles 的表,并且能够使用 PHP API 获得正确的结果。我正在使用 CodeIgniter,因此我将默认的 PHP API 包装为 CodeIgniter 库。
无论如何,这就是我的代码的样子:
$query = $_GET['q'];
$this->load->library('sphinxclient');
$this->sphinxclient->setMatchMode(SPH_MATCH_ANY);
$result = $this->sphinxclient->query($query);
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
数组$to_fetch 包含匹配表行的ID。现在我可以使用典型的 MySQL 查询来让所有相关用户显示在搜索页面上,如下所示:
$query = 'SELECT * FROM profiles WHERE id IN('. join(',', $to_fetch) . ')';
我的问题是:
这是正确的方法吗?或者是否有一个默认的“Sphinx 方式”可以提高性能。
-
其次,我现在得到的只是匹配表行的 id。我还想要列中匹配的部分文本。例如,如果某人搜索关键字
dog,而profiles表中的用户在其about列中包含以下文本:I like dogs. I also like ice cream.
我希望 Sphinx 回来:
I like <strong>dogs</strong>. I also like ice cream.
我该怎么做?我尝试使用 buildExcerpts() 函数,但无法正常工作。
编辑
这就是我现在获得摘录的方式:
// get matched user ids
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
// get user details of matched ids
$members = $this->search_m->get_users_by_id($to_fetch);
// build excerpts
$excerpts = array();
foreach($members as $member) {
$fields = array(
$member['about'],
$member['likes'],
$member['dislikes'],
$member['occupation']
);
$options = array(
'before_match' => '<strong class="match">',
'after_match' => '</strong>',
'chunk_separator' => ' ... ',
'limit' => 60,
'around' => 3,
);
$excerpt_result = $this->sphinxclient->BuildExcerpts($fields, 'profiles', $query, $options);
$excerpts[$member['user_id']] = $excerpt_result;
}
$excerpts_to_return = array();
foreach($excerpts as $key => $excerpt) {
foreach($excerpt as $v) {
if(strpos($v, '<strong class="match">') !== false) {
$excerpts_to_return[$key] = $v;
}
}
}
如您所见,我在 4 个不同的 mysql 列中搜索每个查询:
about
likes
dislikes
occupation
因此,我不知道 4 列中的哪一列包含匹配的关键字。它可以是其中任何一个,甚至不止一个。所以我别无选择,只能通过BuildExcerpts()函数运行所有4列的内容。
即便如此,我也不知道BuildExcerpts() 与<strong class="match"> 标签一起返回了哪一个。因此,我对BuildExcerpts() 返回的所有值运行stpos 检查,以最终获得正确的摘录并将其映射到其个人资料所属的用户。
考虑到我需要匹配 4 个不同列的内容的情况,您有没有比这更好的方法?
【问题讨论】:
标签: php mysql search full-text-search sphinx