-
Notifications
You must be signed in to change notification settings - Fork 25.7k
Implement v_magnitude function #132765
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
svilen-mihaylov-elastic
merged 47 commits into
elastic:main
from
svilen-mihaylov-elastic:svilen/v_magnitude
Aug 14, 2025
Merged
Implement v_magnitude function #132765
Changes from 34 commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
79f6ba4
v_magnitude
svilen-mihaylov-elastic 0a80914
Add verifier test
svilen-mihaylov-elastic 8a9967f
add csv spec test
svilen-mihaylov-elastic c09f349
Add tests
svilen-mihaylov-elastic bf661a5
Fix function
svilen-mihaylov-elastic 035b14d
various fixes
svilen-mihaylov-elastic 722b2f9
floats
svilen-mihaylov-elastic e1e4f96
Fixes
svilen-mihaylov-elastic f9035d6
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 3f7dfb7
Add integration test
svilen-mihaylov-elastic d7bf82a
rename
svilen-mihaylov-elastic e9c5d0c
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 6feed0b
Disable folding for now
svilen-mihaylov-elastic 427c703
Merge branch 'svilen/v_magnitude' of https://github.com/svilen-mihayl…
svilen-mihaylov-elastic cc5f4f7
[CI] Auto commit changes from spotless
a5091ad
Update x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/…
svilen-mihaylov-elastic ad880d9
Update x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/…
svilen-mihaylov-elastic 68d79a4
Update x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/…
svilen-mihaylov-elastic f620f4b
Restore for now
svilen-mihaylov-elastic f6d333c
Use float builder
svilen-mihaylov-elastic 2ce2cf8
Update docs/changelog/132765.yaml
svilen-mihaylov-elastic 4c024b0
[CI] Auto commit changes from spotless
1478fdc
Abstract class with utility fns
svilen-mihaylov-elastic 50dce30
Merge branch 'svilen/v_magnitude' of https://github.com/svilen-mihayl…
svilen-mihaylov-elastic 1f39b8f
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 3743261
Address feedback
svilen-mihaylov-elastic 3ce2f53
Merge with abstract class
svilen-mihaylov-elastic 08ecefd
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 98c3d9b
Fix typing
svilen-mihaylov-elastic 743804c
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 1691bff
Fix test by using List as an input parameter
carlosdelest 5d1effc
Get back row() to being final
carlosdelest bbd72b8
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 612ca48
Fix merge
svilen-mihaylov-elastic 2a9a64d
Add docs
svilen-mihaylov-elastic eb3d0f6
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 84df3be
Update docs/changelog/132765.yaml
svilen-mihaylov-elastic 35b5f6c
Update x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/…
svilen-mihaylov-elastic c542420
Update x-pack/plugin/esql/qa/testFixtures/src/main/resources/vector-m…
svilen-mihaylov-elastic db3e76d
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic b7e9933
Fix merge
svilen-mihaylov-elastic 4c7657a
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic cbd7d33
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic d1b9fbe
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic 0828de8
Fix name
svilen-mihaylov-elastic e24f914
Merge branch 'svilen/v_magnitude' of https://github.com/svilen-mihayl…
svilen-mihaylov-elastic fd46a72
Merge branch 'main' into svilen/v_magnitude
svilen-mihaylov-elastic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| pr: 132765 | ||
| summary: Implement `v_magnitude` function | ||
| area: ES|QL | ||
| type: feature | ||
| issues: [] | ||
1 change: 1 addition & 0 deletions
1
docs/reference/query-languages/esql/images/functions/v_magnitude.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions
12
docs/reference/query-languages/esql/kibana/definition/functions/v_magnitude.json
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
10 changes: 10 additions & 0 deletions
10
docs/reference/query-languages/esql/kibana/docs/functions/v_magnitude.md
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
75 changes: 75 additions & 0 deletions
75
x-pack/plugin/esql/qa/testFixtures/src/main/resources/vector-magnitude.csv-spec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| # Tests for v_magnitude scalar function | ||
|
|
||
| magnitudeWithVectorField | ||
| required_capability: magnitude_scalar_vector_function | ||
|
|
||
| // tag::vector-magnitude[] | ||
| from colors | ||
| | eval magnitude = v_magnitude(rgb_vector) | ||
| | sort magnitude desc, color asc | ||
| // end::vector-magnitude[] | ||
| | limit 10 | ||
| | keep color, magnitude | ||
| ; | ||
|
|
||
| // tag::vector-magnitude-result[] | ||
| color:text | magnitude:double | ||
| white | 441.6729431152344 | ||
| snow | 435.9185791015625 | ||
| azure | 433.1858825683594 | ||
| ivory | 433.1858825683594 | ||
| mint cream | 433.0704345703125 | ||
| sea shell | 426.25579833984375 | ||
| honeydew | 424.5291442871094 | ||
| old lace | 420.6352233886719 | ||
| corn silk | 418.2451477050781 | ||
| linen | 415.93267822265625 | ||
| // end::vector-magnitude-result[] | ||
| ; | ||
|
|
||
| magnitudeAsPartOfExpression | ||
| required_capability: magnitude_scalar_vector_function | ||
|
|
||
| from colors | ||
| | eval score = round((1 + v_magnitude(rgb_vector) / 2), 3) | ||
| | sort score desc, color asc | ||
| | limit 10 | ||
| | keep color, score | ||
| ; | ||
|
|
||
| color:text | score:double | ||
| white | 221.836 | ||
| snow | 218.959 | ||
| azure | 217.593 | ||
| ivory | 217.593 | ||
| mint cream | 217.535 | ||
| sea shell | 214.128 | ||
| honeydew | 213.265 | ||
| old lace | 211.318 | ||
| corn silk | 210.123 | ||
| linen | 208.966 | ||
| ; | ||
|
|
||
| magnitudeWithLiteralVectors | ||
| required_capability: magnitude_scalar_vector_function | ||
|
|
||
| row a = 1 | ||
| | eval magnitude = round(v_magnitude([1, 2, 3]), 3) | ||
| | keep magnitude | ||
| ; | ||
|
|
||
| magnitude:double | ||
| 3.742 | ||
| ; | ||
|
|
||
| magnitudeWithStats | ||
| required_capability: magnitude_scalar_vector_function | ||
|
|
||
| from colors | ||
| | eval magnitude = round(v_magnitude(rgb_vector), 3) | ||
| | stats avg = round(avg(magnitude), 3), min = min(magnitude), max = max(magnitude) | ||
| ; | ||
|
|
||
| avg:double | min:double | max:double | ||
| 313.692 | 0.0 | 441.673 | ||
| ; | ||
svilen-mihaylov-elastic marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
179 changes: 179 additions & 0 deletions
179
...esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/Magnitude.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.esql.expression.function.vector; | ||
|
|
||
| import org.apache.lucene.util.VectorUtil; | ||
| import org.elasticsearch.common.io.stream.NamedWriteableRegistry; | ||
| import org.elasticsearch.common.io.stream.StreamInput; | ||
| import org.elasticsearch.compute.data.Block; | ||
| import org.elasticsearch.compute.data.FloatBlock; | ||
| import org.elasticsearch.compute.data.Page; | ||
| import org.elasticsearch.compute.operator.DriverContext; | ||
| import org.elasticsearch.compute.operator.EvalOperator; | ||
| import org.elasticsearch.xpack.esql.core.expression.Expression; | ||
| import org.elasticsearch.xpack.esql.core.expression.FoldContext; | ||
| import org.elasticsearch.xpack.esql.core.expression.TypeResolutions; | ||
| import org.elasticsearch.xpack.esql.core.expression.function.scalar.UnaryScalarFunction; | ||
| import org.elasticsearch.xpack.esql.core.tree.NodeInfo; | ||
| import org.elasticsearch.xpack.esql.core.tree.Source; | ||
| import org.elasticsearch.xpack.esql.core.type.DataType; | ||
| import org.elasticsearch.xpack.esql.evaluator.mapper.EvaluatorMapper; | ||
| import org.elasticsearch.xpack.esql.expression.function.Example; | ||
| import org.elasticsearch.xpack.esql.expression.function.FunctionAppliesTo; | ||
| import org.elasticsearch.xpack.esql.expression.function.FunctionAppliesToLifecycle; | ||
| import org.elasticsearch.xpack.esql.expression.function.FunctionInfo; | ||
| import org.elasticsearch.xpack.esql.expression.function.Param; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| import static org.elasticsearch.xpack.esql.core.expression.TypeResolutions.isNotNull; | ||
| import static org.elasticsearch.xpack.esql.core.expression.TypeResolutions.isType; | ||
| import static org.elasticsearch.xpack.esql.core.type.DataType.DENSE_VECTOR; | ||
|
|
||
| public class Magnitude extends UnaryScalarFunction implements EvaluatorMapper, VectorFunction { | ||
|
|
||
| public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Hamming", Magnitude::new); | ||
| static final ScalarEvaluatorFunction SCALAR_FUNCTION = Magnitude::calculateScalar; | ||
|
|
||
| @FunctionInfo( | ||
| returnType = "double", | ||
| preview = true, | ||
| description = "Calculates the magnitude of a dense_vector.", | ||
| examples = { @Example(file = "vector-magnitude", tag = "vector-magnitude") }, | ||
| appliesTo = { @FunctionAppliesTo(lifeCycle = FunctionAppliesToLifecycle.DEVELOPMENT) } | ||
| ) | ||
| public Magnitude( | ||
| Source source, | ||
| @Param(name = "input", type = { "dense_vector" }, description = "dense_vector for which to compute the magnitude") Expression input | ||
| ) { | ||
| super(source, input); | ||
| } | ||
|
|
||
| private Magnitude(StreamInput in) throws IOException { | ||
| super(in); | ||
| } | ||
|
|
||
| @Override | ||
| protected UnaryScalarFunction replaceChild(Expression newChild) { | ||
| return new Magnitude(source(), newChild); | ||
| } | ||
|
|
||
| @Override | ||
| protected NodeInfo<? extends Expression> info() { | ||
| return NodeInfo.create(this, Magnitude::new, field()); | ||
| } | ||
|
|
||
| @Override | ||
| public String getWriteableName() { | ||
| return ENTRY.name; | ||
| } | ||
|
|
||
| public static float calculateScalar(float[] scratch) { | ||
| return (float) Math.sqrt(VectorUtil.dotProduct(scratch, scratch)); | ||
svilen-mihaylov-elastic marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| @Override | ||
| public DataType dataType() { | ||
| return DataType.DOUBLE; | ||
| } | ||
|
|
||
| @Override | ||
| protected TypeResolution resolveType() { | ||
| if (childrenResolved() == false) { | ||
| return new TypeResolution("Unresolved children"); | ||
| } | ||
|
|
||
| return isNotNull(field(), sourceText(), TypeResolutions.ParamOrdinal.FIRST).and( | ||
| isType(field(), dt -> dt == DENSE_VECTOR, sourceText(), TypeResolutions.ParamOrdinal.FIRST, "dense_vector") | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Functional interface for evaluating the scalar value of the underlying float array. | ||
| */ | ||
| @FunctionalInterface | ||
| public interface ScalarEvaluatorFunction { | ||
| float calculateScalar(float[] scratch); | ||
| } | ||
|
|
||
| @Override | ||
| public Object fold(FoldContext ctx) { | ||
carlosdelest marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return EvaluatorMapper.super.fold(source(), ctx); | ||
| } | ||
|
|
||
| @Override | ||
| public final EvalOperator.ExpressionEvaluator.Factory toEvaluator(EvaluatorMapper.ToEvaluator toEvaluator) { | ||
| return new ScalarEvaluatorFactory(toEvaluator.apply(field()), SCALAR_FUNCTION, getClass().getSimpleName() + "Evaluator"); | ||
| } | ||
|
|
||
| private record ScalarEvaluatorFactory( | ||
| EvalOperator.ExpressionEvaluator.Factory child, | ||
| ScalarEvaluatorFunction scalarFunction, | ||
| String evaluatorName | ||
| ) implements EvalOperator.ExpressionEvaluator.Factory { | ||
|
|
||
| @Override | ||
| public EvalOperator.ExpressionEvaluator get(DriverContext context) { | ||
| // TODO check whether to use this custom evaluator or reuse / define an existing one | ||
| return new EvalOperator.ExpressionEvaluator() { | ||
| @Override | ||
| public Block eval(Page page) { | ||
| try (FloatBlock block = (FloatBlock) child.get(context).eval(page);) { | ||
| int positionCount = page.getPositionCount(); | ||
| int dimensions = 0; | ||
| // Get the first non-empty vector to calculate the dimension | ||
| for (int p = 0; p < positionCount; p++) { | ||
| if (block.getValueCount(p) != 0) { | ||
| dimensions = block.getValueCount(p); | ||
| break; | ||
| } | ||
| } | ||
| if (dimensions == 0) { | ||
| return context.blockFactory().newConstantFloatBlockWith(0F, 0); | ||
| } | ||
|
|
||
| float[] scratch = new float[dimensions]; | ||
| try (var builder = context.blockFactory().newDoubleBlockBuilder(positionCount * dimensions)) { | ||
| for (int p = 0; p < positionCount; p++) { | ||
| int dims = block.getValueCount(p); | ||
| if (dims == 0) { | ||
| // A null value for the vector, by default append 0 as result. | ||
svilen-mihaylov-elastic marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| builder.appendNull(); | ||
| continue; | ||
| } | ||
| readFloatArray(block, block.getFirstValueIndex(p), dimensions, scratch); | ||
| float result = scalarFunction.calculateScalar(scratch); | ||
| builder.appendDouble(result); | ||
| } | ||
| return builder.build(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return evaluatorName() + "[child=" + child + "]"; | ||
| } | ||
|
|
||
| @Override | ||
| public void close() {} | ||
| }; | ||
| } | ||
|
|
||
| private static void readFloatArray(FloatBlock block, int position, int dimensions, float[] scratch) { | ||
| for (int i = 0; i < dimensions; i++) { | ||
| scratch[i] = block.getFloat(position + i); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return evaluatorName() + "[child=" + child + "]"; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.