A
A
Arthur2018-12-02 18:15:15
Sphinx
Arthur, 2018-12-02 18:15:15

How to generate a Sphinx query in Yii2 (yiisoft/yii2-sphinx component)?

Greetings!
There is a project written in PHP without frameworks, MVC, and so on. When rewriting to Yii2, a question arose with the search through Sphinx. The question is how to set search options like setMatchMode and setSortMode and how to attach buildExcerpts?
The simplest request can be made from the documentation

$rows = (new Query)
            ->from('my_index')
            ->all();

In the documentation about snippets, examples of the form:
$rowSnippetSources[] = file_get_contents('/path/to/index/files/' . $row['id'] . '.txt');

But I don't have these files with ID in the name, only files with project name and different extensions.
Of course, I read the doc, but I did not find the answer
https://github.com/yiisoft/yii2-sphinx/blob/master...
Here is the code that I want to write in Yii2:
$s = new SphinxClient();
    $s->setServer("127.0.0.1", 9312);
    $s->setMatchMode(SPH_MATCH_EXTENDED2);
    $s->setSortMode(SPH_SORT_RELEVANCE);
    $s->SetFieldWeights([
        'name' => 10,
        'desc' => 1,
        'video_text' => 1,
    ]);
    $s->setMaxQueryTime(3000);
    $result = $s->query($name, '*');
    
    $items = [];
    foreach ($result['matches'] as $id => $item) {
        $items[$id] = [
            'name' => $item['attrs']['name'],
            'weight' => $item['weight'],
            'direct' => $item['attrs']['name'] == $name
        ];
        $desc = $s->buildExcerpts([$item['attrs']['desc']], 'my_index', $name, [
            'before_match' => '<strong>',
            'after_match' => '</strong>',
            'around' => 2,
            'limit' => 2,
        ]);
        $items[$id]['desc'] = $desc[0] ?? false;
    }
    usort($items, function ($a, $b) {
        if ($a['direct']) {
            return -1;
        } else {
            return $a['weight'] < $b['weight'];
        }
    });

Actually, the question is how to write this code in Yii2 using the specified component, or can you tell me another component on which this can be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Puma Thailand, 2018-12-02
@ar2rsoft

Use direct SQL queries to the sphinx and everything will be ok

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question