Skip to content

Redisearch compatibility #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Documentation on paginated responses
- Throw custom exception is client is missing
- Add compatibility for Predis version 2.x
- `LOAD ALL` option on Aggregate command (RediSearch `2.0.13`)
- Profile command (RediSearch `2.2.0`) ([Issue#4])
- Vector feature (RediSearch `2.4.0` / `2.4.2`)
- Add `DIALECT` option (RediSearch `2.4.3`) ([Issue#35])
- (dev) Add `make clean` to remove all generated files
- (dev) Add code coverage to `\MacFJA\RediSearch\Index`
- (dev) Add integration test for document insertion
Expand Down Expand Up @@ -222,6 +226,7 @@ First version
[1.0.0]: https://github.com/MacFJA/php-redisearch/releases/tag/1.0.0

[Issue#2]: https://github.com/MacFJA/php-redisearch/issues/2
[Issue#4]: https://github.com/MacFJA/php-redisearch/issues/4
[Issue#5]: https://github.com/MacFJA/php-redisearch/issues/5
[Issue#6]: https://github.com/MacFJA/php-redisearch/issues/6
[Issue#9]: https://github.com/MacFJA/php-redisearch/issues/9
Expand All @@ -230,6 +235,7 @@ First version
[Issue#12]: https://github.com/MacFJA/php-redisearch/issues/12
[Issue#16]: https://github.com/MacFJA/php-redisearch/issues/16
[Issue#26]: https://github.com/MacFJA/php-redisearch/issues/26
[Issue#35]: https://github.com/MacFJA/php-redisearch/issues/35
[Issue#38]: https://github.com/MacFJA/php-redisearch/issues/38
[Issue#39]: https://github.com/MacFJA/php-redisearch/issues/39
[Issue#46]: https://github.com/MacFJA/php-redisearch/issues/46
Expand Down
150 changes: 150 additions & 0 deletions src/Query/Builder/QueryElementVector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?php

declare(strict_types=1);

/*
* Copyright MacFJA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace MacFJA\RediSearch\Query\Builder;

use function array_key_exists;
use function count;
use function gettype;
use function is_int;
use function is_string;
use function strlen;

use InvalidArgumentException;

class QueryElementVector implements QueryElementDecorator
{
private const PARAMETERS = [
'EF_RUNTIME' => 'int',
];

/** @var QueryElement */
private $element;

/** @var int|string */
private $number;

/** @var string */
private $field;

/** @var string */
private $blob;

/** @var null|string */
private $scoreAlias;

/** @var array<string,int|string> */
private $parameters = [];

/**
* @param int|scalar|string $number
*/
public function __construct(QueryElement $element, $number, string $field, string $blob, ?string $scoreAlias = null)
{
if (!is_string($number) && !is_int($number)) {
throw new InvalidArgumentException();
}
$this->element = $element;
$this->number = $number;
$this->field = $field;
$this->blob = $blob;
$this->scoreAlias = $scoreAlias;
}

public function render(?callable $escaper = null): string
{
return sprintf(
'(%s)=>[KNN %s @%s $%s%s%s]',
$this->element->render($escaper),
$this->getRenderedNumber(),
$this->getRenderedField(),
$this->getRenderedBlob(),
$this->getRenderedAttributes(),
$this->getRenderedAlias()
);
}

/**
* @param int|string $value
*
* @return $this
*/
public function addParameter(string $name, $value): self
{
if (!array_key_exists($name, self::PARAMETERS)) {
throw new InvalidArgumentException();
}
if (
!(gettype($value) === self::PARAMETERS[$name])
&& (is_string($value) && (strlen($value) < 2 || !(0 === strpos($value, '$'))))
) {
throw new InvalidArgumentException();
}
$this->parameters[$name] = $value;

return $this;
}

public function priority(): int
{
return self::PRIORITY_BEFORE;
}

public function includeSpace(): bool
{
return false;
}

private function getRenderedNumber(): string
{
return is_string($this->number) ? ('$'.ltrim($this->number, '$')) : ((string) $this->number);
}

private function getRenderedField(): string
{
return ltrim($this->field, '@');
}

private function getRenderedBlob(): string
{
return ltrim($this->blob, '$');
}

private function getRenderedAlias(): string
{
if (!is_string($this->scoreAlias)) {
return '';
}

return ' AS '.$this->scoreAlias;
}

private function getRenderedAttributes(): string
{
if (0 === count($this->parameters)) {
return '';
}

return ' '.implode(' ', array_map(static function ($key, $value) {
return $key.' '.$value;
}, array_keys($this->parameters), array_values($this->parameters)));
}
}
2 changes: 1 addition & 1 deletion src/Redis/Command/AbstractCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
*/
abstract class AbstractCommand implements Command
{
public const MAX_IMPLEMENTED_VERSION = '2.0.12';
public const MAX_IMPLEMENTED_VERSION = '2.4.3';
public const MIN_IMPLEMENTED_VERSION = '2.0.0';

/**
Expand Down
24 changes: 24 additions & 0 deletions src/Redis/Command/AddFieldOptionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use MacFJA\RediSearch\Redis\Command\CreateCommand\NumericFieldOption;
use MacFJA\RediSearch\Redis\Command\CreateCommand\TagFieldOption;
use MacFJA\RediSearch\Redis\Command\CreateCommand\TextFieldOption;
use MacFJA\RediSearch\Redis\Command\CreateCommand\VectorFieldOption;

trait AddFieldOptionTrait
{
Expand Down Expand Up @@ -77,6 +78,17 @@ public function addTagField(string $name, ?string $separator = null, bool $sorta
);
}

public function addVectorField(string $name, string $algorithm, string $type, int $dimension, string $distanceMetric, bool $noIndex = false): self
{
return $this->addField(
(new VectorFieldOption())
->setField($name)
->setAlgorithm($algorithm)
->addAttribute($type, $dimension, $distanceMetric)
->setNoIndex($noIndex)
);
}

public function addJSONTextField(string $path, string $attribute, bool $noStem = false, ?float $weight = null, ?string $phonetic = null, bool $sortable = false, bool $noIndex = false): self
{
return $this->addJSONField(
Expand Down Expand Up @@ -125,6 +137,18 @@ public function addJSONTagField(string $path, string $attribute, ?string $separa
);
}

public function addJSONVectorField(string $path, string $attribute, string $algorithm, string $type, int $dimension, string $distanceMetric, bool $noIndex = false): self
{
return $this->addJSONField(
$path,
(new VectorFieldOption())
->setField($attribute)
->setAlgorithm($algorithm)
->addAttribute($type, $dimension, $distanceMetric)
->setNoIndex($noIndex)
);
}

public function addField(CreateCommandFieldOption $option): self
{
if (!($this instanceof AbstractCommand)) {
Expand Down
19 changes: 19 additions & 0 deletions src/Redis/Command/Aggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use MacFJA\RediSearch\Redis\Command\AggregateCommand\SortByOption;
use MacFJA\RediSearch\Redis\Command\AggregateCommand\WithCursor;
use MacFJA\RediSearch\Redis\Command\Option\CommandOption;
use MacFJA\RediSearch\Redis\Command\Option\CustomValidatorOption as CV;
use MacFJA\RediSearch\Redis\Command\Option\FlagOption;
use MacFJA\RediSearch\Redis\Command\Option\NamedOption;
use MacFJA\RediSearch\Redis\Command\Option\NamelessOption;
Expand All @@ -58,12 +59,14 @@ public function __construct(string $rediSearchVersion = self::MIN_IMPLEMENTED_VE
'query' => new NamelessOption(null, '>=2.0.0'),
'verbatim' => new FlagOption('VERBATIM', false, '>= 2.0.0'),
'load' => new NumberedOption('LOAD', null, '>=2.0.0'),
'loadall' => CV::allowedValues(new NamedOption('LOAD', null, '>=2.0.13'), ['ALL']),
'groupby' => [],
'sortby' => new SortByOption(),
'apply' => [],
'limit' => new LimitOption(),
'filter' => [],
'cursor' => new WithCursor(),
'dialect' => CV::isNumeric(new NamedOption('DIALECT', null, '>=2.4.3')),
], $rediSearchVersion);
}

Expand Down Expand Up @@ -157,6 +160,22 @@ public function setLoad(string ...$field): self
return $this;
}

public function setLoadAll(): self
{
$this->options['load']->setArguments(null);
$this->options['loadall']->setValue('ALL');
$this->lastAdded = $this->options['loadall'];

return $this;
}

public function setDialect(int $version): self
{
$this->options['dialect']->setValue($version);

return $this;
}

public function setWithCursor(?int $count = null, ?int $maxIdle = null): self
{
$this->options['cursor']
Expand Down
3 changes: 2 additions & 1 deletion src/Redis/Command/ConfigSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public function __construct(string $rediSearchVersion = self::MIN_IMPLEMENTED_VE
'action' => new FlagOption('SET', true, '>=2.0.0'),
'options' => [
CustomValidatorOption::allowedValues(new NamelessOption(null, '>=2.0.0 <2.0.6'), ['NOGC', 'MAXEXPANSIONS', 'TIMEOUT', 'ON_TIMEOUT', 'MIN_PHONETIC_TERM_LEN']),
CustomValidatorOption::allowedValues(new NamelessOption(null, '>=2.0.6'), ['NOGC', 'MINPREFIX', 'MAXEXPANSIONS', 'MAXFILTEREXPANSION', 'TIMEOUT', 'ON_TIMEOUT', 'MIN_PHONETIC_TERM_LEN']),
CustomValidatorOption::allowedValues(new NamelessOption(null, '>=2.0.6 <2.4.3'), ['NOGC', 'MINPREFIX', 'MAXEXPANSIONS', 'MAXFILTEREXPANSION', 'TIMEOUT', 'ON_TIMEOUT', 'MIN_PHONETIC_TERM_LEN']),
CustomValidatorOption::allowedValues(new NamelessOption(null, '>=2.4.3'), ['NOGC', 'MINPREFIX', 'MAXEXPANSIONS', 'TIMEOUT', 'ON_TIMEOUT', 'MIN_PHONETIC_TERM_LEN', 'DEFAULT_DIALECT']),
],
'value' => new NamelessOption(null, '>=2.0.0'),
], $rediSearchVersion);
Expand Down
Loading