| 2341 | } |
| 2342 | |
| 2343 | void set_query_vector(QueryTarget &target, const FieldSchema &field_schema, |
| 2344 | const py::object &obj) { |
| 2345 | const DataType data_type = field_schema.data_type(); |
| 2346 | |
| 2347 | // Dense vector data is referenced by the query object. Callers |
| 2348 | // must not modify the source data until the query returns. |
| 2349 | if (FieldSchema::is_dense_vector_field(data_type)) { |
| 2350 | if (!py::isinstance<py::array>(obj)) { |
| 2351 | throw py::type_error("Dense vector[" + field_schema.name() + |
| 2352 | "] expects a ndarray, got " + |
| 2353 | std::string(py::str(py::type::of(obj)))); |
| 2354 | } |
| 2355 | const auto arr = obj.cast<py::array>(); |
| 2356 | if (arr.ndim() != 1) { |
| 2357 | throw py::type_error("Dense vector expects 1D array, got " + |
| 2358 | std::to_string(arr.ndim()) + "D"); |
| 2359 | } |
| 2360 | const auto buf = arr.request(); |
| 2361 | target.clause_ = VectorViewClause{ |
| 2362 | std::string_view(static_cast<const char *>(buf.ptr), |
| 2363 | static_cast<size_t>(buf.size) * buf.itemsize), |
| 2364 | {}, |
| 2365 | {}}; |
| 2366 | return; |
| 2367 | } |
| 2368 | // sparse vector |
| 2369 | if (FieldSchema::is_sparse_vector_field(data_type)) { |
| 2370 | if (!py::isinstance<py::dict>(obj)) { |
| 2371 | throw py::type_error("Sparse vector[" + field_schema.name() + |
| 2372 | "] expects a Python dict, got " + |
| 2373 | std::string(py::str(py::type::of(obj)))); |
| 2374 | } |
| 2375 | const auto sparse = obj.cast<py::dict>(); |
| 2376 | |
| 2377 | switch (data_type) { |
| 2378 | case DataType::SPARSE_VECTOR_FP16: { |
| 2379 | auto [indices, values] = serialize_sparse_vector<ailego::Float16>( |
| 2380 | sparse, [](const py::handle &h, size_t idx) { |
| 2381 | float f = checked_cast<float>( |
| 2382 | h, "Sparse value[" + std::to_string(idx) + "]", "FLOAT"); |
| 2383 | return ailego::Float16(f); |
| 2384 | }); |
| 2385 | target.set_sparse_vector(std::move(indices), std::move(values)); |
| 2386 | break; |
| 2387 | } |
| 2388 | case DataType::SPARSE_VECTOR_FP32: { |
| 2389 | auto [indices, values] = serialize_sparse_vector<float>( |
| 2390 | sparse, [](const py::handle &h, size_t idx) { |
| 2391 | return checked_cast<float>( |
| 2392 | h, "Sparse value[" + std::to_string(idx) + "]", "FLOAT"); |
| 2393 | }); |
| 2394 | target.set_sparse_vector(std::move(indices), std::move(values)); |
| 2395 | break; |
| 2396 | } |
| 2397 | default: |
| 2398 | throw py::type_error("Unsupported sparse vector type: " + |
| 2399 | std::to_string(static_cast<int>(data_type))); |
| 2400 | } |
no test coverage detected