-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSparseVector.php
More file actions
86 lines (69 loc) · 1.89 KB
/
Copy pathSparseVector.php
File metadata and controls
86 lines (69 loc) · 1.89 KB
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
<?php
declare(strict_types = 1);
namespace Spameri\ElasticQuery\Query;
/**
* Sparse vector query (ELSER-style token weights).
*
* Use one of:
* - $inferenceId + $query (use a deployed inference endpoint to expand the text into tokens)
* - $queryVector (provide token => weight pairs directly)
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-sparse-vector-query.html
*/
class SparseVector implements LeafQueryInterface
{
/**
* @param array<string, float>|null $queryVector Token => weight pairs.
* @param array<string, mixed>|null $pruningConfig
*/
public function __construct(
private string $field,
private string|null $inferenceId = null,
private string|null $query = null,
private array|null $queryVector = null,
private bool|null $prune = null,
private array|null $pruningConfig = null,
private float $boost = 1.0,
)
{
$hasInference = $inferenceId !== null && $query !== null;
$hasVector = $queryVector !== null && $queryVector !== [];
if ( ! $hasInference && ! $hasVector) {
throw new \Spameri\ElasticQuery\Exception\InvalidArgumentException(
'SparseVector requires either (inferenceId + query) or queryVector.',
);
}
}
public function key(): string
{
return 'sparse_vector_' . $this->field;
}
/**
* @return array<string, array<string, mixed>>
*/
public function toArray(): array
{
$body = [
'field' => $this->field,
'boost' => $this->boost,
];
if ($this->inferenceId !== null) {
$body['inference_id'] = $this->inferenceId;
}
if ($this->query !== null) {
$body['query'] = $this->query;
}
if ($this->queryVector !== null) {
$body['query_vector'] = $this->queryVector;
}
if ($this->prune !== null) {
$body['prune'] = $this->prune;
}
if ($this->pruningConfig !== null) {
$body['pruning_config'] = $this->pruningConfig;
}
return [
'sparse_vector' => $body,
];
}
}