code: #  Copyright 2023 LanceDB Developers
  #
  #  Licensed under the Apache License, Version 2.0 (the "License");
  #  you may not use this file except in compliance with the License.
  #  You may obtain a copy of the License at
  #      http://www.apache.org/licenses/LICENSE-2.0
  #
  #  Unless required by applicable law or agreed to in writing, software
  #  distributed under the License is distributed on an "AS IS" BASIS,
  #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  #  See the License for the specific language governing permissions and
  #  limitations under the License.
  
  import unittest.mock as mock
  from datetime import timedelta
  
  import lance
  import lancedb
  import numpy as np
  import pandas.testing as tm
  import pyarrow as pa
  import pytest
  import pytest_asyncio
  from lancedb.db import LanceDBConnection
  from lancedb.pydantic import LanceModel, Vector
  from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query
  from lancedb.table import AsyncTable, LanceTable
  
  
  class MockTable:
      def __init__(self, tmp_path):
          self.uri = tmp_path
          self._conn = LanceDBConnection(self.uri)
  
      def to_lance(self):
          return lance.dataset(self.uri)
  
      def _execute_query(self, query):
          ds = self.to_lance()
          return ds.to_table(
              columns=query.columns,
              filter=query.filter,
              prefilter=query.prefilter,
              nearest={
                  "column": query.vector_column,
                  "q": query.vector,
                  "k": query.k,
                  "metric": query.metric,
                  "nprobes": query.nprobes,
                  "refine_factor": query.refine_factor,
              },
          )
  
  
  @pytest.fixture
  def table(tmp_path) -> MockTable:
      df = pa.table(
          {
              "vector": pa.array(
                  [[1, 2], [3, 4]], type=pa.list_(pa.float32(), list_size=2)
              ),
              "id": pa.array([1, 2]),
              "str_field": pa.array(["a", "b"]),
              "float_field": pa.array([1.0, 2.0]),
          }
      )
      lance.write_dataset(df, tmp_path)
      return MockTable(tmp_path)
  
  
  @pytest_asyncio.fixture
  async def table_async(tmp_path) -> AsyncTable:
      conn = await lancedb.connect_async(
          tmp_path, read_consistency_interval=timedelta(seconds=0)
      )
      data = pa.table(
          {
              "vector": pa.array(
                  [[1, 2], [3, 4]], type=pa.list_(pa.float32(), list_size=2)
              ),
              "id": pa.array([1, 2]),
              "str_field": pa.array(["a", "b"]),
              "float_field": pa.array([1.0, 2.0]),
          }
      )
      return await conn.create_table("test", data)
  
  
  def test_cast(table):
      class TestModel(LanceModel):
          vector: Vector(2)
          id: int
          str_field: str
          float_field: float
  
      q = LanceVectorQueryBuilder(table, [0, 0], "vector").limit(1)
      results = q.to_pydantic(TestModel)
      assert len(results) == 1
      r0 = results[0]
      assert isinstance(r0, TestModel)
      assert r0.id == 1
      assert r0.vector == [1, 2]
      assert r0.str_field == "a"
      assert r0.float_field == 1.0
  
  
  def test_query_builder(table):
      rs = (
          LanceVectorQueryBuilder(table, [0, 0], "vector")
          .limit(1)
          .select(["id", "vector"])
          .to_list()
      )
      assert rs[0]["id"] == 1
      assert all(np.array(rs[0]["vector"]) == [1, 2])
  
  
  def test_dynamic_projection(table):
      rs = (
          LanceVectorQueryBuilder(table, [0, 0], "vector")
          .limit(1)
          .select({"id": "id", "id2": "id * 2"})
          .to_list()
      )
      assert rs[0]["id"] == 1
      assert rs[0]["id2"] == 2
  
  
  def test_query_builder_with_filter(table):
      rs = LanceVectorQueryBuilder(table, [0, 0], "vector").where("id = 2").to_list()
      assert rs[0]["id"] == 2
      assert all(np.array(rs[0]["vector"]) == [3, 4])
  
  
  def test_query_builder_with_prefilter(table):
      df = (
          LanceVectorQueryBuilder(table, [0, 0], "vector")
          .where("id = 2")
          .limit(1)
          .to_pandas()
      )
      assert len(df) == 0
  
      df = (
          LanceVectorQueryBuilder(table, [0, 0], "vector")
          .where("id = 2", prefilter=True)
          .limit(1)
          .to_pandas()
      )
      assert df["id"].values[0] == 2
      assert all(df["vector"].values[0] == [3, 4])
  
  
  def test_query_builder_with_metric(table):
      query = [4, 8]
      vector_column_name = "vector"
      df_default = LanceVectorQueryBuilder(table, query, vector_column_name).to_pandas()
      df_l2 = (
          LanceVectorQueryBuilder(table, query, vector_column_name)
          .metric("L2")
          .to_pandas()
      )
      tm.assert_frame_equal(df_default, df_l2)
  
      df_cosine = (
          LanceVectorQueryBuilder(table, query, vector_column_name)
          .metric("cosine")
          .limit(1)
          .to_pandas()
      )
      assert df_cosine._distance[0] == pytest.approx(
          cosine_distance(query, df_cosine.vector[0]),
          abs=1e-6,
      )
      assert 0 <= df_cosine._distance[0] <= 1
  
  
  def test_query_builder_with_different_vector_column():
      table = mock.MagicMock(spec=LanceTable)
      query = [4, 8]
      vector_column_name = "foo_vector"
      builder = (
          LanceVectorQueryBuilder(table, query, vector_column_name)
          .metric("cosine")
          .where("b < 10")
          .select(["b"])
          .limit(2)
      )
      ds = mock.Mock()
      table.to_lance.return_value = ds
      builder.to_arrow()
      table._execute_query.assert_called_once_with(
          Query(
              vector=query,
              filter="b < 10",
              k=2,
              metric="cosine",
              columns=["b"],
              nprobes=20,
              refine_factor=None,
              vector_column="foo_vector",
          )
      )
  
  
  def cosine_distance(vec1, vec2):
      return 1 - np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
  
  
  async def check_query(
      query: AsyncQueryBase, *, expected_num_rows=None, expected_columns=None
  ):
      num_rows = 0
      results = await query.to_batches()
      async for batch in results:
          if expected_columns is not None:
              assert batch.schema.names == expected_columns
          num_rows += batch.num_rows
      if expected_num_rows is not None:
          assert num_rows == expected_num_rows
  
  
  @pytest.mark.asyncio
  async def test_query_async(table_async: AsyncTable):
      await check_query(
          table_async.query(),
          expected_num_rows=2,
          expected_columns=["vector", "id", "str_field", "float_field"],
      )
      await check_query(table_async.query().where("id = 2"), expected_num_rows=1)
      await check_query(
          table_async.query().select(["id", "vector"]), expected_columns=["id", "vector"]
      )
      await check_query(
          table_async.query().select({"foo": "id", "bar": "id + 1"}),
          expected_columns=["foo", "bar"],
      )
      await check_query(table_async.query().limit(1), expected_num_rows=1)
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])), expected_num_rows=2
      )
      # Support different types of inputs for the vector query
      for vector_query in [
          [1, 2],
          [1.0, 2.0],
          np.array([1, 2]),
          (1, 2),
      ]:
          await check_query(
              table_async.query().nearest_to(vector_query), expected_num_rows=2
          )
  
      # No easy way to check these vector query parameters are doing what they say.  We
      # just check that they don't raise exceptions and assume this is tested at a lower
      # level.
      await check_query(
          table_async.query().where("id = 2").nearest_to(pa.array([1, 2])).postfilter(),
          expected_num_rows=1,
      )
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])).refine_factor(1),
          expected_num_rows=2,
      )
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])).nprobes(10),
          expected_num_rows=2,
      )
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])).bypass_vector_index(),
          expected_num_rows=2,
      )
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])).distance_type("dot"),
          expected_num_rows=2,
      )
      await check_query(
          table_async.query().nearest_to(pa.array([1, 2])).distance_type("DoT"),
          expected_num_rows=2,
      )
  
      # Make sure we can use a vector query as a base query (e.g. call limit on it)
      # Also make sure `vector_search` works
      await check_query(table_async.vector_search([1, 2]).limit(1), expected_num_rows=1)
  
      # Also check an empty query
      await check_query(table_async.query().where("id < 0"), expected_num_rows=0)
  
  
  @pytest.mark.asyncio
  async def test_query_to_arrow_async(table_async: AsyncTable):
      table = await table_async.to_arrow()
      assert table.num_rows == 2
      assert table.num_columns == 4
  
      table = await table_async.query().to_arrow()
      assert table.num_rows == 2
      assert table.num_columns == 4
  
      table = await table_async.query().where("id < 0").to_arrow()
      assert table.num_rows == 0
      assert table.num_columns == 4
  
  
  @pytest.mark.asyncio
  async def test_query_to_pandas_async(table_async: AsyncTable):
      df = await table_async.to_pandas()
      assert df.shape == (2, 4)
  
      df = await table_async.query().to_pandas()
      assert df.shape == (2, 4)
  
      df = await table_async.query().where("id < 0").to_pandas()
      assert df.shape == (0, 4)
  
apis: lancedb.pydantic.Vector lancedb.query.LanceVectorQueryBuilder lancedb.query.Query lancedb.db.LanceDBConnection
extract_api: [((2041, 2074), 'lance.write_dataset', 'lance.write_dataset', (['df', 'tmp_path'], {}), '(df, tmp_path)\n', (2060, 2074), False, 'import lance\n'), ((4585, 4625), 'pandas.testing.assert_frame_equal', 'tm.assert_frame_equal', (['df_default', 'df_l2'], {}), '(df_default, df_l2)\n', (4606, 4625), True, 'import pandas.testing as tm\n'), ((5024, 5055), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {'spec': 'LanceTable'}), '(spec=LanceTable)\n', (5038, 5055), True, 'import unittest.mock as mock\n'), ((5302, 5313), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (5311, 5313), True, 'import unittest.mock as mock\n'), ((1097, 1124), 'lancedb.db.LanceDBConnection', 'LanceDBConnection', (['self.uri'], {}), '(self.uri)\n', (1114, 1124), False, 'from lancedb.db import LanceDBConnection\n'), ((1165, 1188), 'lance.dataset', 'lance.dataset', (['self.uri'], {}), '(self.uri)\n', (1178, 1188), False, 'import lance\n'), ((2713, 2722), 'lancedb.pydantic.Vector', 'Vector', (['(2)'], {}), '(2)\n', (2719, 2722), False, 'from lancedb.pydantic import LanceModel, Vector\n'), ((5432, 5569), 'lancedb.query.Query', 'Query', ([], {'vector': 'query', 'filter': '"""b < 10"""', 'k': '(2)', 'metric': '"""cosine"""', 'columns': "['b']", 'nprobes': '(20)', 'refine_factor': 'None', 'vector_column': '"""foo_vector"""'}), "(vector=query, filter='b < 10', k=2, metric='cosine', columns=['b'],\n    nprobes=20, refine_factor=None, vector_column='foo_vector')\n", (5437, 5569), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((7085, 7101), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (7093, 7101), True, 'import numpy as np\n'), ((1907, 1923), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (1915, 1923), True, 'import pyarrow as pa\n'), ((1950, 1970), 'pyarrow.array', 'pa.array', (["['a', 'b']"], {}), "(['a', 'b'])\n", (1958, 1970), True, 'import pyarrow as pa\n'), ((1999, 2019), 'pyarrow.array', 'pa.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (2007, 2019), True, 'import pyarrow as pa\n'), ((2461, 2477), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (2469, 2477), True, 'import pyarrow as pa\n'), ((2504, 2524), 'pyarrow.array', 'pa.array', (["['a', 'b']"], {}), "(['a', 'b'])\n", (2512, 2524), True, 'import pyarrow as pa\n'), ((2553, 2573), 'pyarrow.array', 'pa.array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (2561, 2573), True, 'import pyarrow as pa\n'), ((2798, 2846), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (2821, 2846), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((3319, 3344), 'numpy.array', 'np.array', (["rs[0]['vector']"], {}), "(rs[0]['vector'])\n", (3327, 3344), True, 'import numpy as np\n'), ((3781, 3806), 'numpy.array', 'np.array', (["rs[0]['vector']"], {}), "(rs[0]['vector'])\n", (3789, 3806), True, 'import numpy as np\n'), ((4382, 4439), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', 'query', 'vector_column_name'], {}), '(table, query, vector_column_name)\n', (4405, 4439), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((5729, 5747), 'numpy.dot', 'np.dot', (['vec1', 'vec2'], {}), '(vec1, vec2)\n', (5735, 5747), True, 'import numpy as np\n'), ((2263, 2283), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(0)'}), '(seconds=0)\n', (2272, 2283), False, 'from datetime import timedelta\n'), ((5751, 5771), 'numpy.linalg.norm', 'np.linalg.norm', (['vec1'], {}), '(vec1)\n', (5765, 5771), True, 'import numpy as np\n'), ((5774, 5794), 'numpy.linalg.norm', 'np.linalg.norm', (['vec2'], {}), '(vec2)\n', (5788, 5794), True, 'import numpy as np\n'), ((6909, 6925), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (6917, 6925), True, 'import pyarrow as pa\n'), ((3663, 3711), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (3686, 3711), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((4474, 4531), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', 'query', 'vector_column_name'], {}), '(table, query, vector_column_name)\n', (4497, 4531), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((1847, 1859), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (1857, 1859), True, 'import pyarrow as pa\n'), ((2401, 2413), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (2411, 2413), True, 'import pyarrow as pa\n'), ((7506, 7522), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (7514, 7522), True, 'import pyarrow as pa\n'), ((7635, 7651), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (7643, 7651), True, 'import pyarrow as pa\n'), ((7768, 7784), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (7776, 7784), True, 'import pyarrow as pa\n'), ((7896, 7912), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (7904, 7912), True, 'import pyarrow as pa\n'), ((8034, 8050), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (8042, 8050), True, 'import pyarrow as pa\n'), ((8171, 8187), 'pyarrow.array', 'pa.array', (['[1, 2]'], {}), '([1, 2])\n', (8179, 8187), True, 'import pyarrow as pa\n'), ((3150, 3198), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (3173, 3198), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((3413, 3461), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (3436, 3461), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((3885, 3933), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (3908, 3933), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((4048, 4096), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', '[0, 0]', '"""vector"""'], {}), "(table, [0, 0], 'vector')\n", (4071, 4096), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((4653, 4710), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', 'query', 'vector_column_name'], {}), '(table, query, vector_column_name)\n', (4676, 4710), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n'), ((5137, 5194), 'lancedb.query.LanceVectorQueryBuilder', 'LanceVectorQueryBuilder', (['table', 'query', 'vector_column_name'], {}), '(table, query, vector_column_name)\n', (5160, 5194), False, 'from lancedb.query import AsyncQueryBase, LanceVectorQueryBuilder, Query\n')]