Skip to content

Commit cfe9502

Browse files
committed
Allow converting strings to vectors, so they can be passed into VEC_DISTANCE functions.
1 parent b4bf2b5 commit cfe9502

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

sql/core.go

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package sql
1616

1717
import (
1818
"context"
19+
"encoding/json"
1920
"fmt"
2021
trace2 "runtime/trace"
2122
"strconv"
@@ -317,29 +318,40 @@ func ConvertToVector(v interface{}) ([]float64, error) {
317318
switch b := v.(type) {
318319
case []float64:
319320
return b, nil
321+
case string:
322+
var val interface{}
323+
err := json.Unmarshal([]byte(b), &val)
324+
if err != nil {
325+
return nil, err
326+
}
327+
return convertJsonInterfaceToVector(val)
320328
case JSONWrapper:
321329
val, err := b.ToInterface()
322330
if err != nil {
323331
return nil, err
324332
}
325-
array, ok := val.([]interface{})
326-
if !ok {
327-
return nil, fmt.Errorf("can't convert JSON to vector; expected array, got %v", val)
328-
}
329-
res := make([]float64, len(array))
330-
for i, elem := range array {
331-
floatElem, ok := elem.(float64)
332-
if !ok {
333-
return nil, fmt.Errorf("can't convert JSON to vector; expected array of floats, got %v", elem)
334-
}
335-
res[i] = floatElem
336-
}
337-
return res, nil
333+
return convertJsonInterfaceToVector(val)
338334
default:
339335
return nil, fmt.Errorf("unable to cast %#v of type %T to vector", v, v)
340336
}
341337
}
342338

339+
func convertJsonInterfaceToVector(val interface{}) ([]float64, error) {
340+
array, ok := val.([]interface{})
341+
if !ok {
342+
return nil, fmt.Errorf("can't convert JSON to vector; expected array, got %v", val)
343+
}
344+
res := make([]float64, len(array))
345+
for i, elem := range array {
346+
floatElem, ok := elem.(float64)
347+
if !ok {
348+
return nil, fmt.Errorf("can't convert JSON to vector; expected array of floats, got %v", elem)
349+
}
350+
res[i] = floatElem
351+
}
352+
return res, nil
353+
}
354+
343355
// EvaluateCondition evaluates a condition, which is an expression whose value
344356
// will be nil or coerced boolean.
345357
func EvaluateCondition(ctx *Context, cond Expression, row Row) (interface{}, error) {

0 commit comments

Comments
 (0)