|
| 1 | +// Copyright 2024 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package firestore |
| 16 | + |
| 17 | +// [START firestore_vector_search_distance_result_field] |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "fmt" |
| 21 | + "io" |
| 22 | + |
| 23 | + "cloud.google.com/go/firestore" |
| 24 | +) |
| 25 | + |
| 26 | +func vectorSearchDistanceResultFieldMasked(w io.Writer, projectID string) error { |
| 27 | + ctx := context.Background() |
| 28 | + |
| 29 | + client, err := firestore.NewClient(ctx, projectID) |
| 30 | + if err != nil { |
| 31 | + return fmt.Errorf("firestore.NewClient: %w", err) |
| 32 | + } |
| 33 | + defer client.Close() |
| 34 | + |
| 35 | + collection := client.Collection("coffee-beans") |
| 36 | + |
| 37 | + // Requires a vector index |
| 38 | + // https://firebase.google.com/docs/firestore/vector-search#create_and_manage_vector_indexes |
| 39 | + vectorQuery := collection.Select("color", "vector_distance"). |
| 40 | + FindNearest("embedding_field", |
| 41 | + []float32{3.0, 1.0, 2.0}, |
| 42 | + 10, |
| 43 | + firestore.DistanceMeasureEuclidean, |
| 44 | + &firestore.FindNearestOptions{ |
| 45 | + DistanceResultField: "vector_distance", |
| 46 | + }) |
| 47 | + |
| 48 | + docs, err := vectorQuery.Documents(ctx).GetAll() |
| 49 | + if err != nil { |
| 50 | + fmt.Fprintf(w, "failed to get vector query results: %v", err) |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + for _, doc := range docs { |
| 55 | + fmt.Fprintf(w, "%v, Distance: %v\n", doc.Data()["color"], doc.Data()["vector_distance"]) |
| 56 | + } |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +// [END firestore_vector_search_distance_result_field] |
0 commit comments