findNearest method
Keeps the inputs whose vector field (a String name or a Field) is
nearest to vector (a VectorValue, a List<double> or an
Expression), nearest first.
limit bounds the number of results. With distanceField the computed
distance is added to every result under that name.
Implementation
Pipeline findNearest(
Object field,
Object vector,
DistanceMeasure distanceMeasure, {
int? limit,
String? distanceField,
Map<String, Object?>? rawOptions,
}) {
final Field vectorField = field is Field ? field : Field.of(field);
final Expression vectorExpression;
if (vector is Expression) {
vectorExpression = vector;
} else if (vector is VectorValue) {
vectorExpression = Constant(vector);
} else if (vector is List<double>) {
vectorExpression = Constant(VectorValue(vector));
} else {
throw ArgumentError(
'findNearest() expects a VectorValue, a List<double> or an '
'Expression as the vector, but got: $vector',
);
}
if (limit != null && limit <= 0) {
throw ArgumentError.value(limit, 'limit', 'must be positive');
}
final String measure;
switch (distanceMeasure) {
case DistanceMeasure.euclidean:
measure = 'euclidean';
break;
case DistanceMeasure.cosine:
measure = 'cosine';
break;
case DistanceMeasure.dotProduct:
measure = 'dot_product';
break;
}
return _append(
Stage(
'find_nearest',
args: <pb.Value Function(PipelineEncoder)>[
vectorField.toProto,
vectorExpression.toProto,
(_) => stringValue(measure),
],
options: <String, pb.Value Function(PipelineEncoder)>{
if (limit != null) 'limit': (_) => integerValue(limit),
if (distanceField != null)
'distance_field': Field.of(distanceField).toProto,
},
rawOptions: rawOptions,
),
);
}