-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElasticSearchRepository.php
127 lines (109 loc) · 3.64 KB
/
ElasticSearchRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
namespace LaSalle\Rendimiento\JudithVilela\ImageRegister\Infrastructure\Persistence\Repository;
use Elastica\Index;
use LaSalle\Rendimiento\JudithVilela\ImageRegister\Domain\Model\Aggregate\ImageRegister;
use LaSalle\Rendimiento\JudithVilela\ImageRegister\Infrastructure\Persistence\ElasticSearch;
final class ElasticSearchRepository
{
/** @var ElasticSearch */
private $elasticClient;
/** @var Index */
private $index;
public function __construct()
{
$this->elasticClient = ElasticSearch::instanceElastic();
$this->create();
}
public function create(): void
{
$this->index = $this->elasticClient->getIndex('images');
if (!$this->index->exists()) {
$this->index->create([]);
}
}
public function save(ImageRegister $imageRegister): void
{
$imageId = $imageRegister->id()->getId();
$imageName = $imageRegister->imageName();
$imageFilter = $imageRegister->imageFilter();
$tag = $imageRegister->tags();
$description = $imageRegister->description();
$document = $this->index->createDocument(
$imageId,
[
"imageName" => $imageName,
"filter" => $imageFilter,
"tags" => $tag,
"description" => $description
]
);
$this->index->addDocument($document);
}
public function search(string $searchTerm): array
{
$result = $this->searchFuzzy($searchTerm);
if (empty($result)) {
$result = $this->searchMultiMatch($searchTerm);
}
if (empty($result)) {
$result = $this->searchWildCard($searchTerm);
}
return $result;
}
public function searchWildCard(string $searchTerm): array
{
$result = $this->index->search(
[
"query" => [
"wildcard" =>
[
"tags" => '*' . $searchTerm . '*'
]
]
]
);
return $result->getResults();
}
public function searchMultiMatch(string $searchTerm): array
{
$result = $this->index->search(
[
"query" => [
"multi_match" =>
[
"query" => $searchTerm,
"type" => "best_fields",
"fields" =>
[
"tags",
"description"
],
"operator" => "and"
]
]
]
);
return $result->getResults();
}
public function searchFuzzy(string $searchTerm): array
{
$result = $this->index->search(
[
"query" => [
"fuzzy" =>
[
"tags" =>
[
"value" => $searchTerm,
"boost" => 1,
"fuzziness" => 2,
"prefix_length" => 0,
"max_expansions" => 100
]
]
]
]
);
return $result->getResults();
}
}