| 1 | // Copyright 2024 Lance Developers. |
| 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 | // http://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 | use arrow::array::make_array; |
| 16 | use arrow::array::ArrayData; |
| 17 | use arrow::pyarrow::FromPyArrow; |
| 18 | use lancedb::index::scalar::FullTextSearchQuery; |
| 19 | use lancedb::query::QueryExecutionOptions; |
| 20 | use lancedb::query::{ |
| 21 | ExecutableQuery, Query as LanceDbQuery, QueryBase, Select, VectorQuery as LanceDbVectorQuery, |
| 22 | }; |
| 23 | use pyo3::exceptions::PyRuntimeError; |
| 24 | use pyo3::prelude::{PyAnyMethods, PyDictMethods}; |
| 25 | use pyo3::pymethods; |
| 26 | use pyo3::types::PyDict; |
| 27 | use pyo3::Bound; |
| 28 | use pyo3::PyAny; |
| 29 | use pyo3::PyRef; |
| 30 | use pyo3::PyResult; |
| 31 | use pyo3::{pyclass, PyErr}; |
| 32 | use pyo3_asyncio_0_21::tokio::future_into_py; |
| 33 | |
| 34 | use crate::arrow::RecordBatchStream; |
| 35 | use crate::error::PythonErrorExt; |
| 36 | use crate::util::parse_distance_type; |
| 37 | |
| 38 | #[pyclass] |
| 39 | pub struct Query { |
| 40 | inner: LanceDbQuery, |
| 41 | } |
| 42 | |
| 43 | impl Query { |
| 44 | pub fn new(query: LanceDbQuery) -> Self { |
| 45 | Self { inner: query } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[pymethods] |
| 50 | impl Query { |
| 51 | pub fn r#where(&mut self, predicate: String) { |
| 52 | self.inner = self.inner.clone().only_if(predicate); |
| 53 | } |
| 54 | |
| 55 | pub fn select(&mut self, columns: Vec<(String, String)>) { |
| 56 | self.inner = self.inner.clone().select(Select::dynamic(&columns)); |
| 57 | } |
| 58 | |
| 59 | pub fn select_columns(&mut self, columns: Vec<String>) { |
| 60 | self.inner = self.inner.clone().select(Select::columns(&columns)); |
| 61 | } |
| 62 | |
| 63 | pub fn limit(&mut self, limit: u32) { |
| 64 | self.inner = self.inner.clone().limit(limit as usize); |
| 65 | } |
| 66 | |
| 67 | pub fn offset(&mut self, offset: u32) { |
| 68 | self.inner = self.inner.clone().offset(offset as usize); |
| 69 | } |
| 70 | |
| 71 | pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult<VectorQuery> { |
| 72 | let data: ArrayData = ArrayData::from_pyarrow_bound(&vector)?; |
| 73 | let array = make_array(data); |
| 74 | let inner = self.inner.clone().nearest_to(array).infer_error()?; |
| 75 | Ok(VectorQuery { inner }) |
| 76 | } |
| 77 | |
| 78 | pub fn nearest_to_text(&mut self, query: Bound<'_, PyDict>) -> PyResult<()> { |
| 79 | let query_text = query |
| 80 | .get_item("query")? |
| 81 | .ok_or(PyErr::new::<PyRuntimeError, _>( |
| 82 | "Query text is required for nearest_to_text", |
| 83 | ))? |
| 84 | .extract::<String>()?; |
| 85 | let columns = query |
| 86 | .get_item("columns")? |
| 87 | .map(|columns| columns.extract::<Vec<String>>()) |
| 88 | .transpose()?; |
| 89 | |
| 90 | let fts_query = FullTextSearchQuery::new(query_text).columns(columns); |
| 91 | self.inner = self.inner.clone().full_text_search(fts_query); |
| 92 | |
| 93 | Ok(()) |
| 94 | } |
| 95 | |
| 96 | pub fn execute( |
| 97 | self_: PyRef<'_, Self>, |
| 98 | max_batch_length: Option<u32>, |
| 99 | ) -> PyResult<Bound<'_, PyAny>> { |
| 100 | let inner = self_.inner.clone(); |
| 101 | future_into_py(self_.py(), async move { |
| 102 | let mut opts = QueryExecutionOptions::default(); |
| 103 | if let Some(max_batch_length) = max_batch_length { |
| 104 | opts.max_batch_length = max_batch_length; |
| 105 | } |
| 106 | let inner_stream = inner.execute_with_options(opts).await.infer_error()?; |
| 107 | Ok(RecordBatchStream::new(inner_stream)) |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> { |
| 112 | let inner = self_.inner.clone(); |
| 113 | future_into_py(self_.py(), async move { |
| 114 | inner |
| 115 | .explain_plan(verbose) |
| 116 | .await |
| 117 | .map_err(|e| PyRuntimeError::new_err(e.to_string())) |
| 118 | }) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[pyclass] |
| 123 | pub struct VectorQuery { |
| 124 | inner: LanceDbVectorQuery, |
| 125 | } |
| 126 | |
| 127 | #[pymethods] |
| 128 | impl VectorQuery { |
| 129 | pub fn r#where(&mut self, predicate: String) { |
| 130 | self.inner = self.inner.clone().only_if(predicate); |
| 131 | } |
| 132 | |
| 133 | pub fn select(&mut self, columns: Vec<(String, String)>) { |
| 134 | self.inner = self.inner.clone().select(Select::dynamic(&columns)); |
| 135 | } |
| 136 | |
| 137 | pub fn select_columns(&mut self, columns: Vec<String>) { |
| 138 | self.inner = self.inner.clone().select(Select::columns(&columns)); |
| 139 | } |
| 140 | |
| 141 | pub fn limit(&mut self, limit: u32) { |
| 142 | self.inner = self.inner.clone().limit(limit as usize); |
| 143 | } |
| 144 | |
| 145 | pub fn offset(&mut self, offset: u32) { |
| 146 | self.inner = self.inner.clone().offset(offset as usize); |
| 147 | } |
| 148 | |
| 149 | pub fn column(&mut self, column: String) { |
| 150 | self.inner = self.inner.clone().column(&column); |
| 151 | } |
| 152 | |
| 153 | pub fn distance_type(&mut self, distance_type: String) -> PyResult<()> { |
| 154 | let distance_type = parse_distance_type(distance_type)?; |
| 155 | self.inner = self.inner.clone().distance_type(distance_type); |
| 156 | Ok(()) |
| 157 | } |
| 158 | |
| 159 | pub fn postfilter(&mut self) { |
| 160 | self.inner = self.inner.clone().postfilter(); |
| 161 | } |
| 162 | |
| 163 | pub fn refine_factor(&mut self, refine_factor: u32) { |
| 164 | self.inner = self.inner.clone().refine_factor(refine_factor); |
| 165 | } |
| 166 | |
| 167 | pub fn nprobes(&mut self, nprobe: u32) { |
| 168 | self.inner = self.inner.clone().nprobes(nprobe as usize); |
| 169 | } |
| 170 | |
| 171 | pub fn bypass_vector_index(&mut self) { |
| 172 | self.inner = self.inner.clone().bypass_vector_index() |
| 173 | } |
| 174 | |
| 175 | pub fn execute( |
| 176 | self_: PyRef<'_, Self>, |
| 177 | max_batch_length: Option<u32>, |
| 178 | ) -> PyResult<Bound<'_, PyAny>> { |
| 179 | let inner = self_.inner.clone(); |
| 180 | future_into_py(self_.py(), async move { |
| 181 | let mut opts = QueryExecutionOptions::default(); |
| 182 | if let Some(max_batch_length) = max_batch_length { |
| 183 | opts.max_batch_length = max_batch_length; |
| 184 | } |
| 185 | let inner_stream = inner.execute_with_options(opts).await.infer_error()?; |
| 186 | Ok(RecordBatchStream::new(inner_stream)) |
| 187 | }) |
| 188 | } |
| 189 | |
| 190 | fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> { |
| 191 | let inner = self_.inner.clone(); |
| 192 | future_into_py(self_.py(), async move { |
| 193 | inner |
| 194 | .explain_plan(verbose) |
| 195 | .await |
| 196 | .map_err(|e| PyRuntimeError::new_err(e.to_string())) |
| 197 | }) |
| 198 | } |
| 199 | } |