Laravel 13 与 Elasticsearch 的集成提供了强大的搜索能力,本文介绍如何深度集成 Elasticsearch。

Elasticsearch 配置

连接配置

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
<?php

return [
'default' => env('ELASTIC_CONNECTION', 'default'),

'connections' => [
'default' => [
'hosts' => [
env('ELASTIC_HOST', 'localhost:9200'),
],
'user' => env('ELASTIC_USER', null),
'password' => env('ELASTIC_PASSWORD', null),
'cloud_id' => env('ELASTIC_CLOUD_ID', null),
'api_key' => env('ELASTIC_API_KEY', null),
'retries' => 2,
'timeout' => 10,
],
],

'indices' => [
'products' => [
'alias' => 'products',
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 1,
'analysis' => [
'analyzer' => [
'standard_lowercase' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => ['lowercase'],
],
'ngram_analyzer' => [
'type' => 'custom',
'tokenizer' => 'ngram_tokenizer',
'filter' => ['lowercase'],
],
],
'tokenizer' => [
'ngram_tokenizer' => [
'type' => 'ngram',
'min_gram' => 2,
'max_gram' => 3,
],
],
],
],
'mappings' => [
'properties' => [
'name' => [
'type' => 'text',
'analyzer' => 'standard',
'fields' => [
'keyword' => ['type' => 'keyword'],
'ngram' => ['type' => 'text', 'analyzer' => 'ngram_analyzer'],
],
],
'description' => ['type' => 'text'],
'price' => ['type' => 'float'],
'category_id' => ['type' => 'integer'],
'status' => ['type' => 'keyword'],
'created_at' => ['type' => 'date'],
],
],
],
],
];

Elasticsearch 客户端

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<?php

namespace App\Services\Elasticsearch;

use Elastic\Elasticsearch\Client;
use Elastic\Elasticsearch\ClientBuilder;

class ElasticsearchClient
{
protected Client $client;
protected array $config;

public function __construct(array $config)
{
$this->config = $config;
$this->client = $this->buildClient();
}

protected function buildClient(): Client
{
$builder = ClientBuilder::create()
->setHosts($this->config['hosts'])
->setRetries($this->config['retries'] ?? 2);

if (!empty($this->config['user']) && !empty($this->config['password'])) {
$builder->setBasicAuthentication($this->config['user'], $this->config['password']);
}

if (!empty($this->config['cloud_id'])) {
$builder->setElasticCloudId($this->config['cloud_id']);
}

if (!empty($this->config['api_key'])) {
$builder->setApiKey($this->config['api_key']);
}

return $builder->build();
}

public function getClient(): Client
{
return $this->client;
}

public function index(string $index, array $document, ?string $id = null): array
{
$params = [
'index' => $index,
'body' => $document,
];

if ($id) {
$params['id'] = $id;
}

return $this->client->index($params)->asArray();
}

public function bulk(string $index, array $documents): array
{
$params = ['body' => []];

foreach ($documents as $document) {
$params['body'][] = [
'index' => [
'_index' => $index,
'_id' => $document['id'] ?? null,
],
];
$params['body'][] = $document;
}

return $this->client->bulk($params)->asArray();
}

public function get(string $index, string $id): ?array
{
try {
return $this->client->get([
'index' => $index,
'id' => $id,
])->asArray();
} catch (\Exception $e) {
return null;
}
}

public function search(string $index, array $query): array
{
return $this->client->search([
'index' => $index,
'body' => $query,
])->asArray();
}

public function delete(string $index, string $id): bool
{
try {
$this->client->delete([
'index' => $index,
'id' => $id,
]);
return true;
} catch (\Exception $e) {
return false;
}
}

public function deleteByQuery(string $index, array $query): array
{
return $this->client->deleteByQuery([
'index' => $index,
'body' => $query,
])->asArray();
}

public function createIndex(string $index, array $settings = [], array $mappings = []): array
{
$body = [];

if (!empty($settings)) {
$body['settings'] = $settings;
}

if (!empty($mappings)) {
$body['mappings'] = $mappings;
}

return $this->client->indices()->create([
'index' => $index,
'body' => $body,
])->asArray();
}

public function deleteIndex(string $index): array
{
return $this->client->indices()->delete([
'index' => $index,
])->asArray();
}

public function existsIndex(string $index): bool
{
return $this->client->indices()->exists([
'index' => $index,
])->asBool();
}

public function putMapping(string $index, array $mappings): array
{
return $this->client->indices()->putMapping([
'index' => $index,
'body' => $mappings,
])->asArray();
}

public function refresh(string $index): array
{
return $this->client->indices()->refresh([
'index' => $index,
])->asArray();
}
}

Elasticsearch 搜索引擎

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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
<?php

namespace App\Services\Elasticsearch;

use App\Services\Search\SearchEngineInterface;

class ElasticsearchEngine implements SearchEngineInterface
{
protected ElasticsearchClient $client;

public function __construct(ElasticsearchClient $client)
{
$this->client = $client;
}

public function index(string $index, array $documents): bool
{
if (empty($documents)) {
return true;
}

$result = $this->client->bulk($index, $documents);

return !isset($result['errors']) || !$result['errors'];
}

public function search(string $index, string $query, array $options = []): array
{
$body = $this->buildQuery($query, $options);

$result = $this->client->search($index, $body);

return $this->formatResults($result, $options);
}

public function delete(string $index, string $id): bool
{
return $this->client->delete($index, $id);
}

public function clear(string $index): bool
{
if ($this->client->existsIndex($index)) {
$this->client->deleteIndex($index);
}

$config = config("elasticsearch.indices.{$index}", []);

$this->client->createIndex(
$index,
$config['settings'] ?? [],
$config['mappings'] ?? []
);

return true;
}

protected function buildQuery(string $query, array $options): array
{
$body = [];

if ($query) {
$body['query'] = $this->buildMatchQuery($query, $options);
} else {
$body['query'] = ['match_all' => new \stdClass()];
}

if (!empty($options['filters'])) {
$body['query'] = $this->applyFilters($body['query'], $options['filters']);
}

if (!empty($options['sorts'])) {
$body['sort'] = $this->buildSorts($options['sorts']);
}

$page = $options['page'] ?? 1;
$perPage = $options['per_page'] ?? 15;

$body['from'] = ($page - 1) * $perPage;
$body['size'] = $perPage;

if (!empty($options['highlights'])) {
$body['highlight'] = $this->buildHighlight($options['highlights']);
}

if (!empty($options['aggregations'])) {
$body['aggs'] = $this->buildAggregations($options['aggregations']);
}

return $body;
}

protected function buildMatchQuery(string $query, array $options): array
{
$searchable = $options['searchable'] ?? ['_all'];

if (count($searchable) === 1) {
$field = $searchable[0];
$boost = 1;

if (str_contains($field, '^')) {
[$field, $boost] = explode('^', $field);
}

return [
'match' => [
$field => [
'query' => $query,
'boost' => (float) $boost,
],
],
];
}

$fields = [];
foreach ($searchable as $field) {
if (str_contains($field, '^')) {
$fields[] = $field;
} else {
$fields[] = $field;
}
}

return [
'multi_match' => [
'query' => $query,
'fields' => $fields,
'type' => 'best_fields',
'fuzziness' => 'AUTO',
],
];
}

protected function applyFilters(array $query, array $filters): array
{
$must = [];

foreach ($filters as $filter) {
$must[] = match ($filter['type']) {
'term' => ['term' => [$filter['field'] => $filter['value']]],
'terms' => ['terms' => [$filter['field'] => $filter['values']]],
'range' => $this->buildRangeFilter($filter),
default => [],
};
}

return [
'bool' => [
'must' => [$query],
'filter' => $must,
],
];
}

protected function buildRangeFilter(array $filter): array
{
$range = [];

if (isset($filter['min'])) {
$range['gte'] = $filter['min'];
}

if (isset($filter['max'])) {
$range['lte'] = $filter['max'];
}

return ['range' => [$filter['field'] => $range]];
}

protected function buildSorts(array $sorts): array
{
return array_map(function ($sort) {
return [$sort['field'] => ['order' => $sort['direction']]];
}, $sorts);
}

protected function buildHighlight(array $fields): array
{
return [
'fields' => array_fill_keys($fields, new \stdClass()),
'pre_tags' => ['<em>'],
'post_tags' => ['</em>'],
];
}

protected function buildAggregations(array $aggregations): array
{
$aggs = [];

foreach ($aggregations as $name => $agg) {
$aggs[$name] = match ($agg['type']) {
'terms' => ['terms' => ['field' => $agg['field']]],
'avg' => ['avg' => ['field' => $agg['field']]],
'sum' => ['sum' => ['field' => $agg['field']]],
'max' => ['max' => ['field' => $agg['field']]],
'min' => ['min' => ['field' => $agg['field']]],
default => [],
};
}

return $aggs;
}

protected function formatResults(array $result, array $options): array
{
$hits = [];

foreach ($result['hits']['hits'] ?? [] as $hit) {
$document = $hit['_source'];
$document['id'] = $hit['_id'];
$document['_score'] = $hit['_score'];

if (isset($hit['highlight'])) {
$document['highlight'] = $hit['highlight'];
}

$hits[] = $document;
}

$aggregations = [];
foreach ($result['aggregations'] ?? [] as $name => $agg) {
$aggregations[$name] = $agg;
}

return [
'hits' => $hits,
'total' => $result['hits']['total']['value'] ?? 0,
'aggregations' => $aggregations,
];
}
}

高级搜索功能

模糊搜索

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
<?php

namespace App\Services\Elasticsearch;

class FuzzySearch
{
protected ElasticsearchClient $client;

public function __construct(ElasticsearchClient $client)
{
$this->client = $client;
}

public function search(string $index, string $query, array $fields = ['name']): array
{
$body = [
'query' => [
'bool' => [
'should' => [
[
'multi_match' => [
'query' => $query,
'fields' => $fields,
'type' => 'best_fields',
'fuzziness' => 'AUTO',
'prefix_length' => 2,
],
],
[
'multi_match' => [
'query' => $query,
'fields' => $fields,
'type' => 'phrase',
'boost' => 2,
],
],
],
],
],
];

return $this->client->search($index, $body);
}
}

自动补全

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
<?php

namespace App\Services\Elasticsearch;

class AutocompleteService
{
protected ElasticsearchClient $client;

public function __construct(ElasticsearchClient $client)
{
$this->client = $client;
}

public function suggest(string $index, string $prefix, string $field = 'name', int $size = 10): array
{
$body = [
'suggest' => [
'autocomplete' => [
'prefix' => $prefix,
'completion' => [
'field' => $field . '.suggest',
'size' => $size,
'skip_duplicates' => true,
'fuzzy' => [
'fuzziness' => 1,
],
],
],
],
];

$result = $this->client->search($index, $body);

return array_map(function ($option) {
return [
'text' => $option['text'],
'score' => $option['_score'],
'source' => $option['_source'] ?? null,
];
}, $result['suggest']['autocomplete'][0]['options'] ?? []);
}
}

聚合分析

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
<?php

namespace App\Services\Elasticsearch;

class AggregationService
{
protected ElasticsearchClient $client;

public function __construct(ElasticsearchClient $client)
{
$this->client = $client;
}

public function getStats(string $index, string $field): array
{
$body = [
'size' => 0,
'aggs' => [
'stats' => [
'stats' => ['field' => $field],
],
],
];

$result = $this->client->search($index, $body);

return $result['aggregations']['stats'] ?? [];
}

public function getDistribution(string $index, string $field, int $size = 10): array
{
$body = [
'size' => 0,
'aggs' => [
'distribution' => [
'terms' => [
'field' => $field,
'size' => $size,
],
],
],
];

$result = $this->client->search($index, $body);

return array_map(function ($bucket) {
return [
'key' => $bucket['key'],
'count' => $bucket['doc_count'],
];
}, $result['aggregations']['distribution']['buckets'] ?? []);
}

public function getDateHistogram(string $index, string $field, string $interval = 'day'): array
{
$body = [
'size' => 0,
'aggs' => [
'histogram' => [
'date_histogram' => [
'field' => $field,
'calendar_interval' => $interval,
],
],
],
];

$result = $this->client->search($index, $body);

return array_map(function ($bucket) {
return [
'date' => $bucket['key_as_string'],
'count' => $bucket['doc_count'],
];
}, $result['aggregations']['histogram']['buckets'] ?? []);
}
}

Elasticsearch 命令

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
<?php

namespace App\Console\Commands;

use App\Services\Elasticsearch\ElasticsearchClient;
use Illuminate\Console\Command;

class ElasticsearchCommand extends Command
{
protected $signature = 'elastic:manage {action} {index?} {--create} {--delete}';
protected $description = 'Manage Elasticsearch indices';

public function handle(ElasticsearchClient $client): int
{
$action = $this->argument('action');

return match ($action) {
'list' => $this->listIndices($client),
'create' => $this->createIndex($client),
'delete' => $this->deleteIndex($client),
'status' => $this->showStatus($client),
default => $this->invalidAction(),
};
}

protected function listIndices(ElasticsearchClient $client): int
{
$indices = config('elasticsearch.indices', []);

$this->table(
['Index', 'Status'],
collect($indices)->map(function ($config, $name) use ($client) {
$exists = $client->existsIndex($name) ? 'Created' : 'Not Created';
return [$name, $exists];
})
);

return self::SUCCESS;
}

protected function createIndex(ElasticsearchClient $client): int
{
$index = $this->argument('index');

if (!$index) {
$this->error('Please specify an index name');
return self::FAILURE;
}

$config = config("elasticsearch.indices.{$index}", []);

$client->createIndex(
$index,
$config['settings'] ?? [],
$config['mappings'] ?? []
);

$this->info("Index {$index} created successfully");

return self::SUCCESS;
}

protected function deleteIndex(ElasticsearchClient $client): int
{
$index = $this->argument('index');

if (!$index) {
$this->error('Please specify an index name');
return self::FAILURE;
}

if (!$this->confirm("Are you sure you want to delete index {$index}?")) {
return self::SUCCESS;
}

$client->deleteIndex($index);

$this->info("Index {$index} deleted successfully");

return self::SUCCESS;
}

protected function showStatus(ElasticsearchClient $client): int
{
$index = $this->argument('index');

$this->info('Elasticsearch Status: OK');

return self::SUCCESS;
}

protected function invalidAction(): int
{
$this->error('Invalid action. Use: list, create, delete, or status');
return self::FAILURE;
}
}

总结

Laravel 13 与 Elasticsearch 的深度集成提供了强大的搜索能力,包括全文搜索、模糊匹配、自动补全和聚合分析等功能。通过合理的配置和优化,可以构建高性能的搜索系统。