findNearest method
Returns a VectorQuery that finds the limit documents whose
vectorField (a String or a FieldPath) is nearest to queryVector
according to distanceMeasure.
queryVector is a VectorValue or a List<double>. If
distanceResultField is set, the computed distance is stored in that
field of each returned document. If distanceThreshold is set, only
documents within that threshold are returned.
The search runs on the server only. The filters of this query narrow the candidates; its orderings are superseded by the distance ordering. The documents are read through the converter of this query.
This follows the Android SDK; the JS client SDK has vector search only as a pipeline stage. It needs a vector index on the backend.
final VectorQuerySnapshot<Map<String, Object?>> nearest = await firestore
.collection('coffee-beans')
.findNearest(
vectorField: 'embedding',
queryVector: VectorValue(<double>[0.1, 0.2, 0.3]),
limit: 5,
distanceMeasure: DistanceMeasure.cosine,
)
.get();
Implementation
VectorQuery<T> findNearest({
required Object vectorField,
required Object queryVector,
required int limit,
required DistanceMeasure distanceMeasure,
String? distanceResultField,
double? distanceThreshold,
}) {
final FieldPath fieldPath = _fieldPathOf('findNearest', vectorField);
final VectorValue vector;
if (queryVector is VectorValue) {
vector = queryVector;
} else if (queryVector is List<double>) {
vector = VectorValue(queryVector);
} else {
throw ArgumentError(
'Invalid vector query: the query vector must be a VectorValue or a List<double>, but was ${queryVector.runtimeType}.',
);
}
return VectorQueryInternal.create<T>(
this,
fieldPath,
vector,
limit,
distanceMeasure,
distanceResultField: distanceResultField,
distanceThreshold: distanceThreshold,
);
}