1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Created by PhpStorm. |
5
|
|
|
* User: gordon |
6
|
|
|
* Date: 25/3/2561 |
7
|
|
|
* Time: 1:35 น. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Suilven\ManticoreSearch\Service; |
11
|
|
|
|
12
|
|
|
use Manticoresearch\Search; |
13
|
|
|
use SilverStripe\ORM\ArrayList; |
14
|
|
|
use SilverStripe\ORM\DataObject; |
15
|
|
|
use Suilven\FreeTextSearch\Base\SearcherBase; |
16
|
|
|
use Suilven\FreeTextSearch\Container\SearchResults; |
17
|
|
|
use Suilven\FreeTextSearch\Indexes; |
18
|
|
|
|
19
|
|
|
class Searcher extends SearcherBase implements \Suilven\FreeTextSearch\Interfaces\Searcher |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
private $client; |
23
|
|
|
|
24
|
|
|
public function __construct() |
25
|
|
|
{ |
26
|
|
|
$this->client = new Client(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
public function search(string $q): SearchResults |
31
|
|
|
{ |
32
|
|
|
$client = new Client(); |
33
|
|
|
$manticoreClient = $client->getConnection(); |
34
|
|
|
|
35
|
|
|
$searcher = new Search($manticoreClient); |
36
|
|
|
$searcher->setIndex($this->indexName); |
37
|
|
|
$manticoreResult = $searcher->search($q)->highlight( |
38
|
|
|
[], |
39
|
|
|
['pre_tags' => '<b>', 'post_tags'=>'</b>'], |
40
|
|
|
)->get(); |
41
|
|
|
|
42
|
|
|
$indexes = new Indexes(); |
43
|
|
|
$index = $indexes->getIndex($this->indexName); |
44
|
|
|
$fields = $index->getFields(); |
45
|
|
|
|
46
|
|
|
$ssResult = new ArrayList(); |
47
|
|
|
while ($manticoreResult->valid()) { |
48
|
|
|
$hit = $manticoreResult->current(); |
49
|
|
|
$source = $hit->getData(); |
50
|
|
|
$ssDataObject = new DataObject(); |
51
|
|
|
|
52
|
|
|
// @todo map back likes of title to Title |
53
|
|
|
$keys = \array_keys($source); |
54
|
|
|
foreach ($keys as $key) { |
55
|
|
|
$keyname = $key; |
56
|
|
|
foreach ($fields as $field) { |
57
|
|
|
if (\strtolower($field) === $key) { |
58
|
|
|
$keyname = $field; |
59
|
|
|
|
60
|
|
|
break; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// @todo This is a hack as $Title is rendering the ID in the template |
65
|
|
|
if ($keyname === 'Title') { |
66
|
|
|
$keyname = 'ResultTitle'; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$ssDataObject->Highlights = $hit->getHighlight(); |
70
|
|
|
$ssDataObject->$keyname = $source[$key]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$ssDataObject->ID = $hit->getId(); |
74
|
|
|
$ssResult->push($ssDataObject); |
75
|
|
|
|
76
|
|
|
$manticoreResult->next(); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
// we now need to standardize the output returned |
80
|
|
|
|
81
|
|
|
$searchResults = new SearchResults(); |
82
|
|
|
$searchResults->setRecords($ssResult); |
83
|
|
|
$searchResults->setPage($this->page); |
84
|
|
|
$searchResults->setPageSize($this->pageSize); |
85
|
|
|
$searchResults->setQuery($q); |
86
|
|
|
|
87
|
|
|
return $searchResults; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|