10

我刚从狮身人面像开始。到目前为止,我成功安装了它,profiles在我的 MySQL 数据库上调用了一个表,并且能够使用 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) . ')';

我的问题是:

  1. 这是正确的方法吗?或者是否有默认的“Sphinx 方式”可以更好地提高性能。

  2. 其次,我现在得到的只是匹配表行的 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">因此,我stpos对返回的所有值进行检查,BuildExcerpts()以最终获得正确的摘录并将其映射到其个人资料所属的用户。

考虑到我需要匹配 4 个不同列的内容的情况,您是否看到比这更好的方法?

4

1 回答 1

6

是的,这看起来不错。要记住从 Mysql 返回的行可能不会按照 sphinx 的顺序。

有关如何使用 FIELD() 的信息,请参阅 sphinx 网站上的常见问题解答,但我个人喜欢将 sphinx 中的行放入关联数组中,然后循环遍历我列出的 sphinx 并从数组中获取行。以内存为代价完全避免了排序阶段!

至于突出显示,是的,请坚持使用 buildExcerpts - 这就是这样做的方法。


编辑添加,这个演示 http://nearby.org.uk/sphinx/search-example5-withcomments.phps 演示了从 mysql 获取行和应用程序中的“排序”。并建摘录。

于 2012-06-18T14:13:49.747 回答