mirror of
https://github.com/lancedb/lancedb.git
synced 2025-12-23 05:19:58 +00:00
Compare commits
29 Commits
python-v0.
...
python-v0.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62c5117def | ||
|
|
22c196b3e3 | ||
|
|
1f4ac71fa3 | ||
|
|
b5aad2d856 | ||
|
|
ca6f55b160 | ||
|
|
6f8cf1e068 | ||
|
|
e0277383a5 | ||
|
|
d6b408e26f | ||
|
|
2447372c1f | ||
|
|
f0298d8372 | ||
|
|
54693e6bec | ||
|
|
73b2977bff | ||
|
|
aec85f7875 | ||
|
|
51f92ecb3d | ||
|
|
5b60412d66 | ||
|
|
53d63966a9 | ||
|
|
5ba87575e7 | ||
|
|
cc5f2136a6 | ||
|
|
78e5fb5451 | ||
|
|
8104c5c18e | ||
|
|
4fbabdeec3 | ||
|
|
eb31d95fef | ||
|
|
3169c36525 | ||
|
|
1b990983b3 | ||
|
|
0c21f91c16 | ||
|
|
7e50c239eb | ||
|
|
24e8043150 | ||
|
|
990440385d | ||
|
|
a693a9d897 |
@@ -1,5 +1,5 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 0.4.8
|
current_version = 0.4.10
|
||||||
commit = True
|
commit = True
|
||||||
message = Bump version: {current_version} → {new_version}
|
message = Bump version: {current_version} → {new_version}
|
||||||
tag = True
|
tag = True
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ rustflags = [
|
|||||||
"-Dclippy::dbg_macro",
|
"-Dclippy::dbg_macro",
|
||||||
# not too much we can do to avoid multiple crate versions
|
# not too much we can do to avoid multiple crate versions
|
||||||
"-Aclippy::multiple-crate-versions",
|
"-Aclippy::multiple-crate-versions",
|
||||||
|
"-Aclippy::wildcard_dependencies",
|
||||||
]
|
]
|
||||||
|
|
||||||
[target.x86_64-unknown-linux-gnu]
|
[target.x86_64-unknown-linux-gnu]
|
||||||
@@ -32,3 +33,8 @@ rustflags = ["-C", "target-cpu=haswell", "-C", "target-feature=+avx2,+fma,+f16c"
|
|||||||
|
|
||||||
[target.aarch64-apple-darwin]
|
[target.aarch64-apple-darwin]
|
||||||
rustflags = ["-C", "target-cpu=apple-m1", "-C", "target-feature=+neon,+fp16,+fhm,+dotprod"]
|
rustflags = ["-C", "target-cpu=apple-m1", "-C", "target-feature=+neon,+fp16,+fhm,+dotprod"]
|
||||||
|
|
||||||
|
# Not all Windows systems have the C runtime installed, so this avoids library
|
||||||
|
# not found errors on systems that are missing it.
|
||||||
|
[target.x86_64-pc-windows-msvc]
|
||||||
|
rustflags = ["-Ctarget-feature=+crt-static"]
|
||||||
|
|||||||
17
.github/workflows/npm-publish.yml
vendored
17
.github/workflows/npm-publish.yml
vendored
@@ -80,10 +80,25 @@ jobs:
|
|||||||
- arch: x86_64
|
- arch: x86_64
|
||||||
runner: ubuntu-latest
|
runner: ubuntu-latest
|
||||||
- arch: aarch64
|
- arch: aarch64
|
||||||
runner: buildjet-4vcpu-ubuntu-2204-arm
|
# For successful fat LTO builds, we need a large runner to avoid OOM errors.
|
||||||
|
runner: buildjet-16vcpu-ubuntu-2204-arm
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
# Buildjet aarch64 runners have only 1.5 GB RAM per core, vs 3.5 GB per core for
|
||||||
|
# x86_64 runners. To avoid OOM errors on ARM, we create a swap file.
|
||||||
|
- name: Configure aarch64 build
|
||||||
|
if: ${{ matrix.config.arch == 'aarch64' }}
|
||||||
|
run: |
|
||||||
|
free -h
|
||||||
|
sudo fallocate -l 16G /swapfile
|
||||||
|
sudo chmod 600 /swapfile
|
||||||
|
sudo mkswap /swapfile
|
||||||
|
sudo swapon /swapfile
|
||||||
|
echo "/swapfile swap swap defaults 0 0" >> sudo /etc/fstab
|
||||||
|
# print info
|
||||||
|
swapon --show
|
||||||
|
free -h
|
||||||
- name: Build Linux Artifacts
|
- name: Build Linux Artifacts
|
||||||
run: |
|
run: |
|
||||||
bash ci/build_linux_artifacts.sh ${{ matrix.config.arch }}
|
bash ci/build_linux_artifacts.sh ${{ matrix.config.arch }}
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ keywords = ["lancedb", "lance", "database", "vector", "search"]
|
|||||||
categories = ["database-implementations"]
|
categories = ["database-implementations"]
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
lance = { "version" = "=0.9.15", "features" = ["dynamodb"] }
|
lance = { "version" = "=0.9.18", "features" = ["dynamodb"] }
|
||||||
lance-index = { "version" = "=0.9.15" }
|
lance-index = { "version" = "=0.9.18" }
|
||||||
lance-linalg = { "version" = "=0.9.15" }
|
lance-linalg = { "version" = "=0.9.18" }
|
||||||
lance-testing = { "version" = "=0.9.15" }
|
lance-testing = { "version" = "=0.9.18" }
|
||||||
# Note that this one does not include pyarrow
|
# Note that this one does not include pyarrow
|
||||||
arrow = { version = "50.0", optional = false }
|
arrow = { version = "50.0", optional = false }
|
||||||
arrow-array = "50.0"
|
arrow-array = "50.0"
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ docker build \
|
|||||||
.
|
.
|
||||||
popd
|
popd
|
||||||
|
|
||||||
|
# We turn on memory swap to avoid OOM killer
|
||||||
docker run \
|
docker run \
|
||||||
-v $(pwd):/io -w /io \
|
-v $(pwd):/io -w /io \
|
||||||
|
--memory-swap=-1 \
|
||||||
lancedb-node-manylinux \
|
lancedb-node-manylinux \
|
||||||
bash ci/manylinux_node/build.sh $ARCH
|
bash ci/manylinux_node/build.sh $ARCH
|
||||||
|
|||||||
@@ -90,16 +90,18 @@ nav:
|
|||||||
- Building an ANN index: ann_indexes.md
|
- Building an ANN index: ann_indexes.md
|
||||||
- Vector Search: search.md
|
- Vector Search: search.md
|
||||||
- Full-text search: fts.md
|
- Full-text search: fts.md
|
||||||
- Hybrid search: hybrid_search.md
|
- Hybrid search:
|
||||||
|
- Overview: hybrid_search/hybrid_search.md
|
||||||
|
- Comparing Rerankers: hybrid_search/eval.md
|
||||||
|
- Airbnb financial data example: notebooks/hybrid_search.ipynb
|
||||||
- Filtering: sql.md
|
- Filtering: sql.md
|
||||||
- Versioning & Reproducibility: notebooks/reproducibility.ipynb
|
- Versioning & Reproducibility: notebooks/reproducibility.ipynb
|
||||||
- Configuring Storage: guides/storage.md
|
- Configuring Storage: guides/storage.md
|
||||||
- 🧬 Managing embeddings:
|
- 🧬 Managing embeddings:
|
||||||
- Overview: embeddings/index.md
|
- Overview: embeddings/index.md
|
||||||
- Explicit management: embeddings/embedding_explicit.md
|
- Embedding functions: embeddings/embedding_functions.md
|
||||||
- Implicit management: embeddings/embedding_functions.md
|
- Available models: embeddings/default_embedding_functions.md
|
||||||
- Available Functions: embeddings/default_embedding_functions.md
|
- User-defined embedding functions: embeddings/custom_embedding_function.md
|
||||||
- Custom Embedding Functions: embeddings/api.md
|
|
||||||
- "Example: Multi-lingual semantic search": notebooks/multi_lingual_example.ipynb
|
- "Example: Multi-lingual semantic search": notebooks/multi_lingual_example.ipynb
|
||||||
- "Example: MultiModal CLIP Embeddings": notebooks/DisappearingEmbeddingFunction.ipynb
|
- "Example: MultiModal CLIP Embeddings": notebooks/DisappearingEmbeddingFunction.ipynb
|
||||||
- 🔌 Integrations:
|
- 🔌 Integrations:
|
||||||
@@ -152,16 +154,18 @@ nav:
|
|||||||
- Building an ANN index: ann_indexes.md
|
- Building an ANN index: ann_indexes.md
|
||||||
- Vector Search: search.md
|
- Vector Search: search.md
|
||||||
- Full-text search: fts.md
|
- Full-text search: fts.md
|
||||||
- Hybrid search: hybrid_search.md
|
- Hybrid search:
|
||||||
|
- Overview: hybrid_search/hybrid_search.md
|
||||||
|
- Comparing Rerankers: hybrid_search/eval.md
|
||||||
|
- Airbnb financial data example: notebooks/hybrid_search.ipynb
|
||||||
- Filtering: sql.md
|
- Filtering: sql.md
|
||||||
- Versioning & Reproducibility: notebooks/reproducibility.ipynb
|
- Versioning & Reproducibility: notebooks/reproducibility.ipynb
|
||||||
- Configuring Storage: guides/storage.md
|
- Configuring Storage: guides/storage.md
|
||||||
- Managing Embeddings:
|
- Managing Embeddings:
|
||||||
- Overview: embeddings/index.md
|
- Overview: embeddings/index.md
|
||||||
- Explicit management: embeddings/embedding_explicit.md
|
- Embedding functions: embeddings/embedding_functions.md
|
||||||
- Implicit management: embeddings/embedding_functions.md
|
- Available models: embeddings/default_embedding_functions.md
|
||||||
- Available Functions: embeddings/default_embedding_functions.md
|
- User-defined embedding functions: embeddings/custom_embedding_function.md
|
||||||
- Custom Embedding Functions: embeddings/api.md
|
|
||||||
- "Example: Multi-lingual semantic search": notebooks/multi_lingual_example.ipynb
|
- "Example: Multi-lingual semantic search": notebooks/multi_lingual_example.ipynb
|
||||||
- "Example: MultiModal CLIP Embeddings": notebooks/DisappearingEmbeddingFunction.ipynb
|
- "Example: MultiModal CLIP Embeddings": notebooks/DisappearingEmbeddingFunction.ipynb
|
||||||
- Integrations:
|
- Integrations:
|
||||||
@@ -202,6 +206,7 @@ extra_css:
|
|||||||
|
|
||||||
extra_javascript:
|
extra_javascript:
|
||||||
- "extra_js/init_ask_ai_widget.js"
|
- "extra_js/init_ask_ai_widget.js"
|
||||||
|
- "extra_js/meta_tag.js"
|
||||||
|
|
||||||
extra:
|
extra:
|
||||||
analytics:
|
analytics:
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ Let's implement `SentenceTransformerEmbeddings` class. All you need to do is imp
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
from lancedb.embeddings import register
|
from lancedb.embeddings import register
|
||||||
|
from lancedb.util import attempt_import_or_raise
|
||||||
|
|
||||||
@register("sentence-transformers")
|
@register("sentence-transformers")
|
||||||
class SentenceTransformerEmbeddings(TextEmbeddingFunction):
|
class SentenceTransformerEmbeddings(TextEmbeddingFunction):
|
||||||
@@ -81,7 +82,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
open_clip = self.safe_import("open_clip", "open-clip") # EmbeddingFunction util to import external libs and raise if not found
|
open_clip = attempt_import_or_raise("open_clip", "open-clip") # EmbeddingFunction util to import external libs and raise if not found
|
||||||
model, _, preprocess = open_clip.create_model_and_transforms(
|
model, _, preprocess = open_clip.create_model_and_transforms(
|
||||||
self.name, pretrained=self.pretrained
|
self.name, pretrained=self.pretrained
|
||||||
)
|
)
|
||||||
@@ -109,14 +110,14 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
if isinstance(query, str):
|
if isinstance(query, str):
|
||||||
return [self.generate_text_embeddings(query)]
|
return [self.generate_text_embeddings(query)]
|
||||||
else:
|
else:
|
||||||
PIL = self.safe_import("PIL", "pillow")
|
PIL = attempt_import_or_raise("PIL", "pillow")
|
||||||
if isinstance(query, PIL.Image.Image):
|
if isinstance(query, PIL.Image.Image):
|
||||||
return [self.generate_image_embedding(query)]
|
return [self.generate_image_embedding(query)]
|
||||||
else:
|
else:
|
||||||
raise TypeError("OpenClip supports str or PIL Image as query")
|
raise TypeError("OpenClip supports str or PIL Image as query")
|
||||||
|
|
||||||
def generate_text_embeddings(self, text: str) -> np.ndarray:
|
def generate_text_embeddings(self, text: str) -> np.ndarray:
|
||||||
torch = self.safe_import("torch")
|
torch = attempt_import_or_raise("torch")
|
||||||
text = self.sanitize_input(text)
|
text = self.sanitize_input(text)
|
||||||
text = self._tokenizer(text)
|
text = self._tokenizer(text)
|
||||||
text.to(self.device)
|
text.to(self.device)
|
||||||
@@ -175,7 +176,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
The image to embed. If the image is a str, it is treated as a uri.
|
The image to embed. If the image is a str, it is treated as a uri.
|
||||||
If the image is bytes, it is treated as the raw image bytes.
|
If the image is bytes, it is treated as the raw image bytes.
|
||||||
"""
|
"""
|
||||||
torch = self.safe_import("torch")
|
torch = attempt_import_or_raise("torch")
|
||||||
# TODO handle retry and errors for https
|
# TODO handle retry and errors for https
|
||||||
image = self._to_pil(image)
|
image = self._to_pil(image)
|
||||||
image = self._preprocess(image).unsqueeze(0)
|
image = self._preprocess(image).unsqueeze(0)
|
||||||
@@ -183,7 +184,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
return self._encode_and_normalize_image(image)
|
return self._encode_and_normalize_image(image)
|
||||||
|
|
||||||
def _to_pil(self, image: Union[str, bytes]):
|
def _to_pil(self, image: Union[str, bytes]):
|
||||||
PIL = self.safe_import("PIL", "pillow")
|
PIL = attempt_import_or_raise("PIL", "pillow")
|
||||||
if isinstance(image, bytes):
|
if isinstance(image, bytes):
|
||||||
return PIL.Image.open(io.BytesIO(image))
|
return PIL.Image.open(io.BytesIO(image))
|
||||||
if isinstance(image, PIL.Image.Image):
|
if isinstance(image, PIL.Image.Image):
|
||||||
@@ -9,6 +9,9 @@ Contains the text embedding functions registered by default.
|
|||||||
### Sentence transformers
|
### Sentence transformers
|
||||||
Allows you to set parameters when registering a `sentence-transformers` object.
|
Allows you to set parameters when registering a `sentence-transformers` object.
|
||||||
|
|
||||||
|
!!! info
|
||||||
|
Sentence transformer embeddings are normalized by default. It is recommended to use normalized embeddings for similarity search.
|
||||||
|
|
||||||
| Parameter | Type | Default Value | Description |
|
| Parameter | Type | Default Value | Description |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `name` | `str` | `all-MiniLM-L6-v2` | The name of the model |
|
| `name` | `str` | `all-MiniLM-L6-v2` | The name of the model |
|
||||||
|
|||||||
@@ -1,141 +0,0 @@
|
|||||||
In this workflow, you define your own embedding function and pass it as a callable to LanceDB, invoking it in your code to generate the embeddings. Let's look at some examples.
|
|
||||||
|
|
||||||
### Hugging Face
|
|
||||||
|
|
||||||
!!! note
|
|
||||||
Currently, the Hugging Face method is only supported in the Python SDK.
|
|
||||||
|
|
||||||
=== "Python"
|
|
||||||
The most popular open source option is to use the [sentence-transformers](https://www.sbert.net/)
|
|
||||||
library, which can be installed via pip.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install sentence-transformers
|
|
||||||
```
|
|
||||||
|
|
||||||
The example below shows how to use the `paraphrase-albert-small-v2` model to generate embeddings
|
|
||||||
for a given document.
|
|
||||||
|
|
||||||
```python
|
|
||||||
from sentence_transformers import SentenceTransformer
|
|
||||||
|
|
||||||
name="paraphrase-albert-small-v2"
|
|
||||||
model = SentenceTransformer(name)
|
|
||||||
|
|
||||||
# used for both training and querying
|
|
||||||
def embed_func(batch):
|
|
||||||
return [model.encode(sentence) for sentence in batch]
|
|
||||||
```
|
|
||||||
|
|
||||||
### OpenAI
|
|
||||||
|
|
||||||
Another popular alternative is to use an external API like OpenAI's [embeddings API](https://platform.openai.com/docs/guides/embeddings/what-are-embeddings).
|
|
||||||
|
|
||||||
=== "Python"
|
|
||||||
```python
|
|
||||||
import openai
|
|
||||||
import os
|
|
||||||
|
|
||||||
# Configuring the environment variable OPENAI_API_KEY
|
|
||||||
if "OPENAI_API_KEY" not in os.environ:
|
|
||||||
# OR set the key here as a variable
|
|
||||||
openai.api_key = "sk-..."
|
|
||||||
|
|
||||||
# verify that the API key is working
|
|
||||||
assert len(openai.Model.list()["data"]) > 0
|
|
||||||
|
|
||||||
def embed_func(c):
|
|
||||||
rs = openai.Embedding.create(input=c, engine="text-embedding-ada-002")
|
|
||||||
return [record["embedding"] for record in rs["data"]]
|
|
||||||
```
|
|
||||||
|
|
||||||
=== "JavaScript"
|
|
||||||
```javascript
|
|
||||||
const lancedb = require("vectordb");
|
|
||||||
|
|
||||||
// You need to provide an OpenAI API key
|
|
||||||
const apiKey = "sk-..."
|
|
||||||
// The embedding function will create embeddings for the 'text' column
|
|
||||||
const embedding = new lancedb.OpenAIEmbeddingFunction('text', apiKey)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Applying an embedding function to data
|
|
||||||
|
|
||||||
=== "Python"
|
|
||||||
Using an embedding function, you can apply it to raw data
|
|
||||||
to generate embeddings for each record.
|
|
||||||
|
|
||||||
Say you have a pandas DataFrame with a `text` column that you want embedded,
|
|
||||||
you can use the `with_embeddings` function to generate embeddings and add them to
|
|
||||||
an existing table.
|
|
||||||
|
|
||||||
```python
|
|
||||||
import pandas as pd
|
|
||||||
from lancedb.embeddings import with_embeddings
|
|
||||||
|
|
||||||
df = pd.DataFrame(
|
|
||||||
[
|
|
||||||
{"text": "pepperoni"},
|
|
||||||
{"text": "pineapple"}
|
|
||||||
]
|
|
||||||
)
|
|
||||||
data = with_embeddings(embed_func, df)
|
|
||||||
|
|
||||||
# The output is used to create / append to a table
|
|
||||||
# db.create_table("my_table", data=data)
|
|
||||||
```
|
|
||||||
|
|
||||||
If your data is in a different column, you can specify the `column` kwarg to `with_embeddings`.
|
|
||||||
|
|
||||||
By default, LanceDB calls the function with batches of 1000 rows. This can be configured
|
|
||||||
using the `batch_size` parameter to `with_embeddings`.
|
|
||||||
|
|
||||||
LanceDB automatically wraps the function with retry and rate-limit logic to ensure the OpenAI
|
|
||||||
API call is reliable.
|
|
||||||
|
|
||||||
=== "JavaScript"
|
|
||||||
Using an embedding function, you can apply it to raw data
|
|
||||||
to generate embeddings for each record.
|
|
||||||
|
|
||||||
Simply pass the embedding function created above and LanceDB will use it to generate
|
|
||||||
embeddings for your data.
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const db = await lancedb.connect("data/sample-lancedb");
|
|
||||||
const data = [
|
|
||||||
{ text: "pepperoni"},
|
|
||||||
{ text: "pineapple"}
|
|
||||||
]
|
|
||||||
|
|
||||||
const table = await db.createTable("vectors", data, embedding)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Querying using an embedding function
|
|
||||||
|
|
||||||
!!! warning
|
|
||||||
At query time, you **must** use the same embedding function you used to vectorize your data.
|
|
||||||
If you use a different embedding function, the embeddings will not reside in the same vector
|
|
||||||
space and the results will be nonsensical.
|
|
||||||
|
|
||||||
=== "Python"
|
|
||||||
```python
|
|
||||||
query = "What's the best pizza topping?"
|
|
||||||
query_vector = embed_func([query])[0]
|
|
||||||
results = (
|
|
||||||
tbl.search(query_vector)
|
|
||||||
.limit(10)
|
|
||||||
.to_pandas()
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
The above snippet returns a pandas DataFrame with the 10 closest vectors to the query.
|
|
||||||
|
|
||||||
=== "JavaScript"
|
|
||||||
```javascript
|
|
||||||
const results = await table
|
|
||||||
.search("What's the best pizza topping?")
|
|
||||||
.limit(10)
|
|
||||||
.execute()
|
|
||||||
```
|
|
||||||
|
|
||||||
The above snippet returns an array of records with the top 10 nearest neighbors to the query.
|
|
||||||
@@ -3,61 +3,126 @@ Representing multi-modal data as vector embeddings is becoming a standard practi
|
|||||||
For this purpose, LanceDB introduces an **embedding functions API**, that allow you simply set up once, during the configuration stage of your project. After this, the table remembers it, effectively making the embedding functions *disappear in the background* so you don't have to worry about manually passing callables, and instead, simply focus on the rest of your data engineering pipeline.
|
For this purpose, LanceDB introduces an **embedding functions API**, that allow you simply set up once, during the configuration stage of your project. After this, the table remembers it, effectively making the embedding functions *disappear in the background* so you don't have to worry about manually passing callables, and instead, simply focus on the rest of your data engineering pipeline.
|
||||||
|
|
||||||
!!! warning
|
!!! warning
|
||||||
Using the implicit embeddings management approach means that you can forget about the manually passing around embedding
|
Using the embedding function registry means that you don't have to explicitly generate the embeddings yourself.
|
||||||
functions in your code, as long as you don't intend to change it at a later time. If your embedding function changes,
|
However, if your embedding function changes, you'll have to re-configure your table with the new embedding function
|
||||||
you'll have to re-configure your table with the new embedding function and regenerate the embeddings.
|
and regenerate the embeddings. In the future, we plan to support the ability to change the embedding function via
|
||||||
|
table metadata and have LanceDB automatically take care of regenerating the embeddings.
|
||||||
|
|
||||||
|
|
||||||
## 1. Define the embedding function
|
## 1. Define the embedding function
|
||||||
We have some pre-defined embedding functions in the global registry, with more coming soon. Here's let's an implementation of CLIP as example.
|
|
||||||
```
|
|
||||||
registry = EmbeddingFunctionRegistry.get_instance()
|
|
||||||
clip = registry.get("open-clip").create()
|
|
||||||
|
|
||||||
```
|
=== "Python"
|
||||||
You can also define your own embedding function by implementing the `EmbeddingFunction` abstract base interface. It subclasses Pydantic Model which can be utilized to write complex schemas simply as we'll see next!
|
In the LanceDB python SDK, we define a global embedding function registry with
|
||||||
|
many different embedding models and even more coming soon.
|
||||||
|
Here's let's an implementation of CLIP as example.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from lancedb.embeddings import get_registry
|
||||||
|
|
||||||
|
registry = get_registry()
|
||||||
|
clip = registry.get("open-clip").create()
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also define your own embedding function by implementing the `EmbeddingFunction`
|
||||||
|
abstract base interface. It subclasses Pydantic Model which can be utilized to write complex schemas simply as we'll see next!
|
||||||
|
|
||||||
|
=== "JavaScript""
|
||||||
|
In the TypeScript SDK, the choices are more limited. For now, only the OpenAI
|
||||||
|
embedding function is available.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const lancedb = require("vectordb");
|
||||||
|
|
||||||
|
// You need to provide an OpenAI API key
|
||||||
|
const apiKey = "sk-..."
|
||||||
|
// The embedding function will create embeddings for the 'text' column
|
||||||
|
const embedding = new lancedb.OpenAIEmbeddingFunction('text', apiKey)
|
||||||
|
```
|
||||||
|
|
||||||
## 2. Define the data model or schema
|
## 2. Define the data model or schema
|
||||||
The embedding function defined above abstracts away all the details about the models and dimensions required to define the schema. You can simply set a field as **source** or **vector** column. Here's how:
|
|
||||||
|
|
||||||
```python
|
=== "Python"
|
||||||
class Pets(LanceModel):
|
The embedding function defined above abstracts away all the details about the models and dimensions required to define the schema. You can simply set a field as **source** or **vector** column. Here's how:
|
||||||
vector: Vector(clip.ndims) = clip.VectorField()
|
|
||||||
image_uri: str = clip.SourceField()
|
|
||||||
```
|
|
||||||
|
|
||||||
`VectorField` tells LanceDB to use the clip embedding function to generate query embeddings for the `vector` column and `SourceField` ensures that when adding data, we automatically use the specified embedding function to encode `image_uri`.
|
```python
|
||||||
|
class Pets(LanceModel):
|
||||||
|
vector: Vector(clip.ndims) = clip.VectorField()
|
||||||
|
image_uri: str = clip.SourceField()
|
||||||
|
```
|
||||||
|
|
||||||
## 3. Create LanceDB table
|
`VectorField` tells LanceDB to use the clip embedding function to generate query embeddings for the `vector` column and `SourceField` ensures that when adding data, we automatically use the specified embedding function to encode `image_uri`.
|
||||||
Now that we have chosen/defined our embedding function and the schema, we can create the table:
|
|
||||||
|
|
||||||
```python
|
=== "JavaScript"
|
||||||
db = lancedb.connect("~/lancedb")
|
|
||||||
table = db.create_table("pets", schema=Pets)
|
|
||||||
|
|
||||||
```
|
For the TypeScript SDK, a schema can be inferred from input data, or an explicit
|
||||||
|
Arrow schema can be provided.
|
||||||
|
|
||||||
That's it! We've provided all the information needed to embed the source and query inputs. We can now forget about the model and dimension details and start to build our VectorDB pipeline.
|
## 3. Create table and add data
|
||||||
|
|
||||||
## 4. Ingest lots of data and query your table
|
Now that we have chosen/defined our embedding function and the schema,
|
||||||
Any new or incoming data can just be added and it'll be vectorized automatically.
|
we can create the table and ingest data without needing to explicitly generate
|
||||||
|
the embeddings at all:
|
||||||
|
|
||||||
```python
|
=== "Python"
|
||||||
table.add([{"image_uri": u} for u in uris])
|
```python
|
||||||
```
|
db = lancedb.connect("~/lancedb")
|
||||||
|
table = db.create_table("pets", schema=Pets)
|
||||||
|
|
||||||
Our OpenCLIP query embedding function supports querying via both text and images:
|
table.add([{"image_uri": u} for u in uris])
|
||||||
|
```
|
||||||
|
|
||||||
```python
|
=== "JavaScript"
|
||||||
result = table.search("dog")
|
|
||||||
```
|
|
||||||
|
|
||||||
Let's query an image:
|
```javascript
|
||||||
|
const db = await lancedb.connect("data/sample-lancedb");
|
||||||
|
const data = [
|
||||||
|
{ text: "pepperoni"},
|
||||||
|
{ text: "pineapple"}
|
||||||
|
]
|
||||||
|
|
||||||
```python
|
const table = await db.createTable("vectors", data, embedding)
|
||||||
p = Path("path/to/images/samoyed_100.jpg")
|
```
|
||||||
query_image = Image.open(p)
|
|
||||||
table.search(query_image)
|
## 4. Querying your table
|
||||||
```
|
Not only can you forget about the embeddings during ingestion, you also don't
|
||||||
|
need to worry about it when you query the table:
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
|
||||||
|
Our OpenCLIP query embedding function supports querying via both text and images:
|
||||||
|
|
||||||
|
```python
|
||||||
|
results = (
|
||||||
|
table.search("dog")
|
||||||
|
.limit(10)
|
||||||
|
.to_pandas()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Or we can search using an image:
|
||||||
|
|
||||||
|
```python
|
||||||
|
p = Path("path/to/images/samoyed_100.jpg")
|
||||||
|
query_image = Image.open(p)
|
||||||
|
results = (
|
||||||
|
table.search(query_image)
|
||||||
|
.limit(10)
|
||||||
|
.to_pandas()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Both of the above snippet returns a pandas DataFrame with the 10 closest vectors to the query.
|
||||||
|
|
||||||
|
=== "JavaScript"
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const results = await table
|
||||||
|
.search("What's the best pizza topping?")
|
||||||
|
.limit(10)
|
||||||
|
.execute()
|
||||||
|
```
|
||||||
|
|
||||||
|
The above snippet returns an array of records with the top 10 nearest neighbors to the query.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -100,4 +165,5 @@ rs[2].image
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
Now that you have the basic idea about implicit management via embedding functions, let's dive deeper into a [custom API](./api.md) that you can use to implement your own embedding functions.
|
Now that you have the basic idea about LanceDB embedding functions and the embedding function registry,
|
||||||
|
let's dive deeper into defining your own [custom functions](./custom_embedding_function.md).
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
Due to the nature of vector embeddings, they can be used to represent any kind of data, from text to images to audio. This makes them a very powerful tool for machine learning practitioners. However, there's no one-size-fits-all solution for generating embeddings - there are many different libraries and APIs (both commercial and open source) that can be used to generate embeddings from structured/unstructured data.
|
Due to the nature of vector embeddings, they can be used to represent any kind of data, from text to images to audio.
|
||||||
|
This makes them a very powerful tool for machine learning practitioners.
|
||||||
|
However, there's no one-size-fits-all solution for generating embeddings - there are many different libraries and APIs
|
||||||
|
(both commercial and open source) that can be used to generate embeddings from structured/unstructured data.
|
||||||
|
|
||||||
LanceDB supports 2 methods of vectorizing your raw data into embeddings.
|
LanceDB supports 3 methods of working with embeddings.
|
||||||
|
|
||||||
1. **Explicit**: By manually calling LanceDB's `with_embedding` function to vectorize your data via an `embed_func` of your choice
|
1. You can manually generate embeddings for the data and queries. This is done outside of LanceDB.
|
||||||
2. **Implicit**: Allow LanceDB to embed the data and queries in the background as they come in, by using the table's `EmbeddingRegistry` information
|
2. You can use the built-in [embedding functions](./embedding_functions.md) to embed the data and queries in the background.
|
||||||
|
3. For python users, you can define your own [custom embedding function](./custom_embedding_function.md)
|
||||||
|
that extends the default embedding functions.
|
||||||
|
|
||||||
See the [explicit](embedding_explicit.md) and [implicit](embedding_functions.md) embedding sections for more details.
|
For python users, there is also a legacy [with_embeddings API](./legacy.md).
|
||||||
|
It is retained for compatibility and will be removed in a future version.
|
||||||
99
docs/src/embeddings/legacy.md
Normal file
99
docs/src/embeddings/legacy.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
The legacy `with_embeddings` API is for Python only and is deprecated.
|
||||||
|
|
||||||
|
### Hugging Face
|
||||||
|
|
||||||
|
The most popular open source option is to use the [sentence-transformers](https://www.sbert.net/)
|
||||||
|
library, which can be installed via pip.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install sentence-transformers
|
||||||
|
```
|
||||||
|
|
||||||
|
The example below shows how to use the `paraphrase-albert-small-v2` model to generate embeddings
|
||||||
|
for a given document.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
|
||||||
|
name="paraphrase-albert-small-v2"
|
||||||
|
model = SentenceTransformer(name)
|
||||||
|
|
||||||
|
# used for both training and querying
|
||||||
|
def embed_func(batch):
|
||||||
|
return [model.encode(sentence) for sentence in batch]
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### OpenAI
|
||||||
|
|
||||||
|
Another popular alternative is to use an external API like OpenAI's [embeddings API](https://platform.openai.com/docs/guides/embeddings/what-are-embeddings).
|
||||||
|
|
||||||
|
```python
|
||||||
|
import openai
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Configuring the environment variable OPENAI_API_KEY
|
||||||
|
if "OPENAI_API_KEY" not in os.environ:
|
||||||
|
# OR set the key here as a variable
|
||||||
|
openai.api_key = "sk-..."
|
||||||
|
|
||||||
|
client = openai.OpenAI()
|
||||||
|
|
||||||
|
def embed_func(c):
|
||||||
|
rs = client.embeddings.create(input=c, model="text-embedding-ada-002")
|
||||||
|
return [record.embedding for record in rs["data"]]
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Applying an embedding function to data
|
||||||
|
|
||||||
|
Using an embedding function, you can apply it to raw data
|
||||||
|
to generate embeddings for each record.
|
||||||
|
|
||||||
|
Say you have a pandas DataFrame with a `text` column that you want embedded,
|
||||||
|
you can use the `with_embeddings` function to generate embeddings and add them to
|
||||||
|
an existing table.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pandas as pd
|
||||||
|
from lancedb.embeddings import with_embeddings
|
||||||
|
|
||||||
|
df = pd.DataFrame(
|
||||||
|
[
|
||||||
|
{"text": "pepperoni"},
|
||||||
|
{"text": "pineapple"}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
data = with_embeddings(embed_func, df)
|
||||||
|
|
||||||
|
# The output is used to create / append to a table
|
||||||
|
tbl = db.create_table("my_table", data=data)
|
||||||
|
```
|
||||||
|
|
||||||
|
If your data is in a different column, you can specify the `column` kwarg to `with_embeddings`.
|
||||||
|
|
||||||
|
By default, LanceDB calls the function with batches of 1000 rows. This can be configured
|
||||||
|
using the `batch_size` parameter to `with_embeddings`.
|
||||||
|
|
||||||
|
LanceDB automatically wraps the function with retry and rate-limit logic to ensure the OpenAI
|
||||||
|
API call is reliable.
|
||||||
|
|
||||||
|
## Querying using an embedding function
|
||||||
|
|
||||||
|
!!! warning
|
||||||
|
At query time, you **must** use the same embedding function you used to vectorize your data.
|
||||||
|
If you use a different embedding function, the embeddings will not reside in the same vector
|
||||||
|
space and the results will be nonsensical.
|
||||||
|
|
||||||
|
=== "Python"
|
||||||
|
```python
|
||||||
|
query = "What's the best pizza topping?"
|
||||||
|
query_vector = embed_func([query])[0]
|
||||||
|
results = (
|
||||||
|
tbl.search(query_vector)
|
||||||
|
.limit(10)
|
||||||
|
.to_pandas()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
The above snippet returns a pandas DataFrame with the 10 closest vectors to the query.
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import pickle
|
import pickle
|
||||||
import re
|
import re
|
||||||
import sys
|
|
||||||
import zipfile
|
import zipfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|||||||
6
docs/src/extra_js/meta_tag.js
Normal file
6
docs/src/extra_js/meta_tag.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
window.addEventListener('load', function() {
|
||||||
|
var meta = document.createElement('meta');
|
||||||
|
meta.setAttribute('property', 'og:image');
|
||||||
|
meta.setAttribute('content', '/assets/lancedb_and_lance.png');
|
||||||
|
document.head.appendChild(meta);
|
||||||
|
});
|
||||||
49
docs/src/hybrid_search/eval.md
Normal file
49
docs/src/hybrid_search/eval.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# Hybrid Search
|
||||||
|
|
||||||
|
Hybrid Search is a broad (often misused) term. It can mean anything from combining multiple methods for searching, to applying ranking methods to better sort the results. In this blog, we use the definition of "hybrid search" to mean using a combination of keyword-based and vector search.
|
||||||
|
|
||||||
|
## The challenge of (re)ranking search results
|
||||||
|
Once you have a group of the most relevant search results from multiple search sources, you'd likely standardize the score and rank them accordingly. This process can also be seen as another independent step - reranking.
|
||||||
|
There are two approaches for reranking search results from multiple sources.
|
||||||
|
* <b>Score-based</b>: Calculate final relevance scores based on a weighted linear combination of individual search algorithm scores. Example - Weighted linear combination of semantic search & keyword-based search results.
|
||||||
|
* <b>Relevance-based</b>: Discards the existing scores and calculates the relevance of each search result - query pair. Example - Cross Encoder models
|
||||||
|
|
||||||
|
Even though there are many strategies for reranking search results, none works for all cases. Moreover, evaluating them itself is a challenge. Also, reranking can be dataset, application specific so it's hard to generalize.
|
||||||
|
|
||||||
|
### Example evaluation of hybrid search with Reranking
|
||||||
|
|
||||||
|
Here's some evaluation numbers from experiment comparing these re-rankers on about 800 queries. It is modified version of an evaluation script from [llama-index](https://github.com/run-llama/finetune-embedding/blob/main/evaluate.ipynb) that measures hit-rate at top-k.
|
||||||
|
|
||||||
|
<b> With OpenAI ada2 embedding </b>
|
||||||
|
|
||||||
|
Vector Search baseline - `0.64`
|
||||||
|
|
||||||
|
| Reranker | Top-3 | Top-5 | Top-10 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Linear Combination | `0.73` | `0.74` | `0.85` |
|
||||||
|
| Cross Encoder | `0.71` | `0.70` | `0.77` |
|
||||||
|
| Cohere | `0.81` | `0.81` | `0.85` |
|
||||||
|
| ColBERT | `0.68` | `0.68` | `0.73` |
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="https://github.com/AyushExel/assets/assets/15766192/d57b1780-ef27-414c-a5c3-73bee7808a45">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<b> With OpenAI embedding-v3-small </b>
|
||||||
|
|
||||||
|
Vector Search baseline - `0.59`
|
||||||
|
|
||||||
|
| Reranker | Top-3 | Top-5 | Top-10 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Linear Combination | `0.68` | `0.70` | `0.84` |
|
||||||
|
| Cross Encoder | `0.72` | `0.72` | `0.79` |
|
||||||
|
| Cohere | `0.79` | `0.79` | `0.84` |
|
||||||
|
| ColBERT | `0.70` | `0.70` | `0.76` |
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="https://github.com/AyushExel/assets/assets/15766192/259adfd2-6ec6-4df6-a77d-1456598970dd">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
### Conclusion
|
||||||
|
|
||||||
|
The results show that the reranking methods are able to improve the search results. However, the improvement is not consistent across all rerankers. The choice of reranker depends on the dataset and the application. It is also important to note that the reranking methods are not a replacement for the search methods. They are complementary and should be used together to get the best results. The speed to recall tradeoff is also an important factor to consider when choosing the reranker.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Hybrid Search
|
# Hybrid Search
|
||||||
|
|
||||||
LanceDB supports both semantic and keyword-based search. In real world applications, it is often useful to combine these two approaches to get the best best results. For example, you may want to search for a document that is semantically similar to a query document, but also contains a specific keyword. This is an example of *hybrid search*, a search algorithm that combines multiple search techniques.
|
LanceDB supports both semantic and keyword-based search (also termed full-text search, or FTS). In real world applications, it is often useful to combine these two approaches to get the best best results. For example, you may want to search for a document that is semantically similar to a query document, but also contains a specific keyword. This is an example of *hybrid search*, a search algorithm that combines multiple search techniques.
|
||||||
|
|
||||||
## Hybrid search in LanceDB
|
## Hybrid search in LanceDB
|
||||||
You can perform hybrid search in LanceDB by combining the results of semantic and full-text search via a reranking algorithm of your choice. LanceDB provides multiple rerankers out of the box. However, you can always write a custom reranker if your use case need more sophisticated logic .
|
You can perform hybrid search in LanceDB by combining the results of semantic and full-text search via a reranking algorithm of your choice. LanceDB provides multiple rerankers out of the box. However, you can always write a custom reranker if your use case need more sophisticated logic .
|
||||||
@@ -69,7 +69,7 @@ reranker = LinearCombinationReranker(weight=0.3) # Use 0.3 as the weight for vec
|
|||||||
results = table.search("rebel", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
results = table.search("rebel", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
||||||
```
|
```
|
||||||
|
|
||||||
Arguments
|
### Arguments
|
||||||
----------------
|
----------------
|
||||||
* `weight`: `float`, default `0.7`:
|
* `weight`: `float`, default `0.7`:
|
||||||
The weight to use for the semantic search score. The weight for the full-text search score is `1 - weights`.
|
The weight to use for the semantic search score. The weight for the full-text search score is `1 - weights`.
|
||||||
@@ -91,9 +91,9 @@ reranker = CohereReranker()
|
|||||||
results = table.search("vampire weekend", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
results = table.search("vampire weekend", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
||||||
```
|
```
|
||||||
|
|
||||||
Arguments
|
### Arguments
|
||||||
----------------
|
----------------
|
||||||
* `model_name`` : str, default `"rerank-english-v2.0"``
|
* `model_name` : str, default `"rerank-english-v2.0"`
|
||||||
The name of the cross encoder model to use. Available cohere models are:
|
The name of the cross encoder model to use. Available cohere models are:
|
||||||
- rerank-english-v2.0
|
- rerank-english-v2.0
|
||||||
- rerank-multilingual-v2.0
|
- rerank-multilingual-v2.0
|
||||||
@@ -117,7 +117,7 @@ results = table.search("harmony hall", query_type="hybrid").rerank(reranker=rera
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Arguments
|
### Arguments
|
||||||
----------------
|
----------------
|
||||||
* `model` : str, default `"cross-encoder/ms-marco-TinyBERT-L-6"`
|
* `model` : str, default `"cross-encoder/ms-marco-TinyBERT-L-6"`
|
||||||
The name of the cross encoder model to use. Available cross encoder models can be found [here](https://www.sbert.net/docs/pretrained_cross-encoders.html)
|
The name of the cross encoder model to use. Available cross encoder models can be found [here](https://www.sbert.net/docs/pretrained_cross-encoders.html)
|
||||||
@@ -143,7 +143,7 @@ reranker = ColbertReranker()
|
|||||||
results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
||||||
```
|
```
|
||||||
|
|
||||||
Arguments
|
### Arguments
|
||||||
----------------
|
----------------
|
||||||
* `model_name` : `str`, default `"colbert-ir/colbertv2.0"`
|
* `model_name` : `str`, default `"colbert-ir/colbertv2.0"`
|
||||||
The name of the cross encoder model to use.
|
The name of the cross encoder model to use.
|
||||||
@@ -162,7 +162,8 @@ This reranker uses the OpenAI API to combine the results of semantic and full-te
|
|||||||
This prompts chat model to rerank results which is not a dedicated reranker model. This should be treated as experimental.
|
This prompts chat model to rerank results which is not a dedicated reranker model. This should be treated as experimental.
|
||||||
|
|
||||||
!!! Tip
|
!!! Tip
|
||||||
You might run out of token limit so set the search `limits` based on your token limit.
|
- You might run out of token limit so set the search `limits` based on your token limit.
|
||||||
|
- It is recommended to use gpt-4-turbo-preview, the default model, older models might lead to undesired behaviour
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from lancedb.rerankers import OpenaiReranker
|
from lancedb.rerankers import OpenaiReranker
|
||||||
@@ -172,15 +173,15 @@ reranker = OpenaiReranker()
|
|||||||
results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
|
||||||
```
|
```
|
||||||
|
|
||||||
Arguments
|
### Arguments
|
||||||
----------------
|
----------------
|
||||||
`model_name` : `str`, default `"gpt-3.5-turbo-1106"`
|
* `model_name` : `str`, default `"gpt-4-turbo-preview"`
|
||||||
The name of the cross encoder model to use.
|
The name of the cross encoder model to use.
|
||||||
`column` : `str`, default `"text"`
|
* `column` : `str`, default `"text"`
|
||||||
The name of the column to use as input to the cross encoder model.
|
The name of the column to use as input to the cross encoder model.
|
||||||
`return_score` : `str`, default `"relevance"`
|
* `return_score` : `str`, default `"relevance"`
|
||||||
options are "relevance" or "all". Only "relevance" is supported for now.
|
options are "relevance" or "all". Only "relevance" is supported for now.
|
||||||
`api_key` : `str`, default `None`
|
* `api_key` : `str`, default `None`
|
||||||
The API key to use. If None, will use the OPENAI_API_KEY environment variable.
|
The API key to use. If None, will use the OPENAI_API_KEY environment variable.
|
||||||
|
|
||||||
|
|
||||||
@@ -212,24 +213,30 @@ class MyReranker(Reranker):
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also accept additional arguments like a filter along with fts and vector search results
|
### Example of a Custom Reranker
|
||||||
|
For the sake of simplicity let's build custom reranker that just enchances the Cohere Reranker by accepting a filter query, and accept other CohereReranker params as kwags.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|
||||||
from lancedb.rerankers import Reranker
|
from typing import List, Union
|
||||||
import pyarrow as pa
|
import pandas as pd
|
||||||
|
from lancedb.rerankers import CohereReranker
|
||||||
|
|
||||||
class MyReranker(Reranker):
|
class MofidifiedCohereReranker(CohereReranker):
|
||||||
...
|
def __init__(self, filters: Union[str, List[str]], **kwargs):
|
||||||
|
super().__init__(**kwargs)
|
||||||
def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table, filter: str):
|
filters = filters if isinstance(filters, list) else [filters]
|
||||||
# Use the built-in merging function
|
self.filters = filters
|
||||||
combined_result = self.merge_results(vector_results, fts_results)
|
|
||||||
|
|
||||||
# Do something with the combined results & filter
|
|
||||||
# ...
|
|
||||||
|
|
||||||
# Return the combined results
|
def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table)-> pa.Table:
|
||||||
return combined_result
|
combined_result = super().rerank_hybrid(query, vector_results, fts_results)
|
||||||
|
df = combined_result.to_pandas()
|
||||||
|
for filter in self.filters:
|
||||||
|
df = df.query("not text.str.contains(@filter)")
|
||||||
|
|
||||||
|
return pa.Table.from_pandas(df)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
!!! tip
|
||||||
|
The `vector_results` and `fts_results` are pyarrow tables. You can convert them to pandas dataframes using `to_pandas()` method and perform any operations you want. After you are done, you can convert the dataframe back to pyarrow table using `pa.Table.from_pandas()` method and return it.
|
||||||
@@ -290,7 +290,7 @@
|
|||||||
"from lancedb.pydantic import LanceModel, Vector\n",
|
"from lancedb.pydantic import LanceModel, Vector\n",
|
||||||
"\n",
|
"\n",
|
||||||
"class Pets(LanceModel):\n",
|
"class Pets(LanceModel):\n",
|
||||||
" vector: Vector(clip.ndims) = clip.VectorField()\n",
|
" vector: Vector(clip.ndims()) = clip.VectorField()\n",
|
||||||
" image_uri: str = clip.SourceField()\n",
|
" image_uri: str = clip.SourceField()\n",
|
||||||
"\n",
|
"\n",
|
||||||
" @property\n",
|
" @property\n",
|
||||||
@@ -360,7 +360,7 @@
|
|||||||
" table = db.create_table(\"pets\", schema=Pets)\n",
|
" table = db.create_table(\"pets\", schema=Pets)\n",
|
||||||
" # use a sampling of 1000 images\n",
|
" # use a sampling of 1000 images\n",
|
||||||
" p = Path(\"~/Downloads/images\").expanduser()\n",
|
" p = Path(\"~/Downloads/images\").expanduser()\n",
|
||||||
" uris = [str(f) for f in p.iterdir()]\n",
|
" uris = [str(f) for f in p.glob(\"*.jpg\")]\n",
|
||||||
" uris = sample(uris, 1000)\n",
|
" uris = sample(uris, 1000)\n",
|
||||||
" table.add(pd.DataFrame({\"image_uri\": uris}))"
|
" table.add(pd.DataFrame({\"image_uri\": uris}))"
|
||||||
]
|
]
|
||||||
@@ -543,7 +543,7 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"from PIL import Image\n",
|
"from PIL import Image\n",
|
||||||
"p = Path(\"/Users/changshe/Downloads/images/samoyed_100.jpg\")\n",
|
"p = Path(\"~/Downloads/images/samoyed_100.jpg\").expanduser()\n",
|
||||||
"query_image = Image.open(p)\n",
|
"query_image = Image.open(p)\n",
|
||||||
"query_image"
|
"query_image"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -23,10 +23,8 @@ from multiprocessing import Pool
|
|||||||
import lance
|
import lance
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
from datasets import load_dataset
|
from datasets import load_dataset
|
||||||
from PIL import Image
|
|
||||||
from transformers import CLIPModel, CLIPProcessor, CLIPTokenizerFast
|
from transformers import CLIPModel, CLIPProcessor, CLIPTokenizerFast
|
||||||
|
|
||||||
import lancedb
|
|
||||||
|
|
||||||
MODEL_ID = "openai/clip-vit-base-patch32"
|
MODEL_ID = "openai/clip-vit-base-patch32"
|
||||||
|
|
||||||
|
|||||||
1122
docs/src/notebooks/hybrid_search.ipynb
Normal file
1122
docs/src/notebooks/hybrid_search.ipynb
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,9 @@
|
|||||||
# DuckDB
|
# DuckDB
|
||||||
|
|
||||||
LanceDB is very well-integrated with [DuckDB](https://duckdb.org/), an in-process SQL OLAP database. This integration is done via [Arrow](https://duckdb.org/docs/guides/python/sql_on_arrow) .
|
In Python, LanceDB tables can also be queried with [DuckDB](https://duckdb.org/), an in-process SQL OLAP database. This means you can write complex SQL queries to analyze your data in LanceDB.
|
||||||
|
|
||||||
|
This integration is done via [Apache Arrow](https://duckdb.org/docs/guides/python/sql_on_arrow), which provides zero-copy data sharing between LanceDB and DuckDB. DuckDB is capable of passing down column selections and basic filters to LanceDB, reducing the amount of data that needs to be scanned to perform your query. Finally, the integration allows streaming data from LanceDB tables, allowing you to aggregate tables that won't fit into memory. All of this uses the same mechanism described in DuckDB's blog post *[DuckDB quacks Arrow](https://duckdb.org/2021/12/03/duck-arrow.html)*.
|
||||||
|
|
||||||
|
|
||||||
We can demonstrate this by first installing `duckdb` and `lancedb`.
|
We can demonstrate this by first installing `duckdb` and `lancedb`.
|
||||||
|
|
||||||
@@ -19,14 +22,15 @@ data = [
|
|||||||
{"vector": [5.9, 26.5], "item": "bar", "price": 20.0}
|
{"vector": [5.9, 26.5], "item": "bar", "price": 20.0}
|
||||||
]
|
]
|
||||||
table = db.create_table("pd_table", data=data)
|
table = db.create_table("pd_table", data=data)
|
||||||
arrow_table = table.to_arrow()
|
|
||||||
```
|
```
|
||||||
|
|
||||||
DuckDB can directly query the `pyarrow.Table` object:
|
To query the table, first call `to_lance` to convert the table to a "dataset", which is an object that can be queried by DuckDB. Then all you need to do is reference that dataset by the same name in your SQL query.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import duckdb
|
import duckdb
|
||||||
|
|
||||||
|
arrow_table = table.to_lance()
|
||||||
|
|
||||||
duckdb.query("SELECT * FROM arrow_table")
|
duckdb.query("SELECT * FROM arrow_table")
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ excluded_globs = [
|
|||||||
"../src/concepts/*.md",
|
"../src/concepts/*.md",
|
||||||
"../src/ann_indexes.md",
|
"../src/ann_indexes.md",
|
||||||
"../src/basic.md",
|
"../src/basic.md",
|
||||||
"../src/hybrid_search.md",
|
"../src/hybrid_search/hybrid_search.md",
|
||||||
]
|
]
|
||||||
|
|
||||||
python_prefix = "py"
|
python_prefix = "py"
|
||||||
|
|||||||
44
node/package-lock.json
generated
44
node/package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "vectordb",
|
"name": "vectordb",
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "vectordb",
|
"name": "vectordb",
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64",
|
"x64",
|
||||||
"arm64"
|
"arm64"
|
||||||
@@ -53,11 +53,11 @@
|
|||||||
"uuid": "^9.0.0"
|
"uuid": "^9.0.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@lancedb/vectordb-darwin-arm64": "0.4.8",
|
"@lancedb/vectordb-darwin-arm64": "0.4.10",
|
||||||
"@lancedb/vectordb-darwin-x64": "0.4.8",
|
"@lancedb/vectordb-darwin-x64": "0.4.10",
|
||||||
"@lancedb/vectordb-linux-arm64-gnu": "0.4.8",
|
"@lancedb/vectordb-linux-arm64-gnu": "0.4.10",
|
||||||
"@lancedb/vectordb-linux-x64-gnu": "0.4.8",
|
"@lancedb/vectordb-linux-x64-gnu": "0.4.10",
|
||||||
"@lancedb/vectordb-win32-x64-msvc": "0.4.8"
|
"@lancedb/vectordb-win32-x64-msvc": "0.4.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@75lb/deep-merge": {
|
"node_modules/@75lb/deep-merge": {
|
||||||
@@ -329,9 +329,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@lancedb/vectordb-darwin-arm64": {
|
"node_modules/@lancedb/vectordb-darwin-arm64": {
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.8.tgz",
|
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz",
|
||||||
"integrity": "sha512-FpnJaw7KmNdD/FtOw9AcmPL5P+L04AcnfPj9ZyEjN8iCwB/qaOGYgdfBv+EbEtfHIsqA12q/1BRduu9KdB6BIA==",
|
"integrity": "sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -341,9 +341,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@lancedb/vectordb-darwin-x64": {
|
"node_modules/@lancedb/vectordb-darwin-x64": {
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.8.tgz",
|
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.10.tgz",
|
||||||
"integrity": "sha512-RafOEYyZIgphp8wPGuVLFaTc8aAqo0NCO1LQMx0mB0xV96vrdo0Mooivs+dYN3RFfSHtTKPw9O1Jc957Vp1TLg==",
|
"integrity": "sha512-XbfR58OkQpAe0xMSTrwJh9ZjGSzG9EZ7zwO6HfYem8PxcLYAcC6eWRWoSG/T0uObyrPTcYYyvHsp0eNQWYBFAQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -353,9 +353,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@lancedb/vectordb-linux-arm64-gnu": {
|
"node_modules/@lancedb/vectordb-linux-arm64-gnu": {
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.8.tgz",
|
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.10.tgz",
|
||||||
"integrity": "sha512-WlbYNfj4+v1hBHUluF+hnlG/A0ZaQFdXBTGDfHQniL11o+n3emWm4ujP5nSAoQHXjSH9DaOTGr/N4Mc9Xe+luw==",
|
"integrity": "sha512-x40WKH9b+KxorRmKr9G7fv8p5mMj8QJQvRMA0v6v+nbZHr2FLlAZV+9mvhHOnm4AGIkPP5335cUgv6Qz6hgwkQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@@ -365,9 +365,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@lancedb/vectordb-linux-x64-gnu": {
|
"node_modules/@lancedb/vectordb-linux-x64-gnu": {
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.8.tgz",
|
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.10.tgz",
|
||||||
"integrity": "sha512-z+qFJrDqnNEv4JcwYDyt51PHmWjuM/XaOlSjpBnyyuUImeY+QcwctMuyXt8+Q4zhuqQR1AhLKrMwCU+YmMfk5g==",
|
"integrity": "sha512-CTGPpuzlqq2nVjUxI9gAJOT1oBANIovtIaFsOmBSnEAHgX7oeAxKy2b6L/kJzsgqSzvR5vfLwYcWFrr6ZmBxSA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -377,9 +377,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@lancedb/vectordb-win32-x64-msvc": {
|
"node_modules/@lancedb/vectordb-win32-x64-msvc": {
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.8.tgz",
|
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.10.tgz",
|
||||||
"integrity": "sha512-VjUryVvEA04r0j4lU9pJy84cmjuQm1GhBzbPc8kwbn5voT4A6BPglrlNsU0Zc+j8Fbjyvauzw2lMEcMsF4F0rw==",
|
"integrity": "sha512-Fd7r74coZyrKzkfXg4WthqOL+uKyJyPTia6imcrMNqKOlTGdKmHf02Qi2QxWZrFaabkRYo4Tpn5FeRJ3yYX8CA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "vectordb",
|
"name": "vectordb",
|
||||||
"version": "0.4.8",
|
"version": "0.4.10",
|
||||||
"description": " Serverless, low-latency vector database for AI applications",
|
"description": " Serverless, low-latency vector database for AI applications",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"types": "dist/index.d.ts",
|
"types": "dist/index.d.ts",
|
||||||
@@ -85,10 +85,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@lancedb/vectordb-darwin-arm64": "0.4.8",
|
"@lancedb/vectordb-darwin-arm64": "0.4.10",
|
||||||
"@lancedb/vectordb-darwin-x64": "0.4.8",
|
"@lancedb/vectordb-darwin-x64": "0.4.10",
|
||||||
"@lancedb/vectordb-linux-arm64-gnu": "0.4.8",
|
"@lancedb/vectordb-linux-arm64-gnu": "0.4.10",
|
||||||
"@lancedb/vectordb-linux-x64-gnu": "0.4.8",
|
"@lancedb/vectordb-linux-x64-gnu": "0.4.10",
|
||||||
"@lancedb/vectordb-win32-x64-msvc": "0.4.8"
|
"@lancedb/vectordb-win32-x64-msvc": "0.4.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,8 +14,6 @@
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Field,
|
Field,
|
||||||
type FixedSizeListBuilder,
|
|
||||||
Float32,
|
|
||||||
makeBuilder,
|
makeBuilder,
|
||||||
RecordBatchFileWriter,
|
RecordBatchFileWriter,
|
||||||
Utf8,
|
Utf8,
|
||||||
@@ -26,14 +24,19 @@ import {
|
|||||||
Table as ArrowTable,
|
Table as ArrowTable,
|
||||||
RecordBatchStreamWriter,
|
RecordBatchStreamWriter,
|
||||||
List,
|
List,
|
||||||
Float64,
|
|
||||||
RecordBatch,
|
RecordBatch,
|
||||||
makeData,
|
makeData,
|
||||||
Struct,
|
Struct,
|
||||||
type Float
|
type Float,
|
||||||
|
DataType,
|
||||||
|
Binary,
|
||||||
|
Float32
|
||||||
} from 'apache-arrow'
|
} from 'apache-arrow'
|
||||||
import { type EmbeddingFunction } from './index'
|
import { type EmbeddingFunction } from './index'
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Options to control how a column should be converted to a vector array
|
||||||
|
*/
|
||||||
export class VectorColumnOptions {
|
export class VectorColumnOptions {
|
||||||
/** Vector column type. */
|
/** Vector column type. */
|
||||||
type: Float = new Float32()
|
type: Float = new Float32()
|
||||||
@@ -45,14 +48,50 @@ export class VectorColumnOptions {
|
|||||||
|
|
||||||
/** Options to control the makeArrowTable call. */
|
/** Options to control the makeArrowTable call. */
|
||||||
export class MakeArrowTableOptions {
|
export class MakeArrowTableOptions {
|
||||||
/** Provided schema. */
|
/*
|
||||||
|
* Schema of the data.
|
||||||
|
*
|
||||||
|
* If this is not provided then the data type will be inferred from the
|
||||||
|
* JS type. Integer numbers will become int64, floating point numbers
|
||||||
|
* will become float64 and arrays will become variable sized lists with
|
||||||
|
* the data type inferred from the first element in the array.
|
||||||
|
*
|
||||||
|
* The schema must be specified if there are no records (e.g. to make
|
||||||
|
* an empty table)
|
||||||
|
*/
|
||||||
schema?: Schema
|
schema?: Schema
|
||||||
|
|
||||||
/** Vector columns */
|
/*
|
||||||
|
* Mapping from vector column name to expected type
|
||||||
|
*
|
||||||
|
* Lance expects vector columns to be fixed size list arrays (i.e. tensors)
|
||||||
|
* However, `makeArrowTable` will not infer this by default (it creates
|
||||||
|
* variable size list arrays). This field can be used to indicate that a column
|
||||||
|
* should be treated as a vector column and converted to a fixed size list.
|
||||||
|
*
|
||||||
|
* The keys should be the names of the vector columns. The value specifies the
|
||||||
|
* expected data type of the vector columns.
|
||||||
|
*
|
||||||
|
* If `schema` is provided then this field is ignored.
|
||||||
|
*
|
||||||
|
* By default, the column named "vector" will be assumed to be a float32
|
||||||
|
* vector column.
|
||||||
|
*/
|
||||||
vectorColumns: Record<string, VectorColumnOptions> = {
|
vectorColumns: Record<string, VectorColumnOptions> = {
|
||||||
vector: new VectorColumnOptions()
|
vector: new VectorColumnOptions()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If true then string columns will be encoded with dictionary encoding
|
||||||
|
*
|
||||||
|
* Set this to true if your string columns tend to repeat the same values
|
||||||
|
* often. For more precise control use the `schema` property to specify the
|
||||||
|
* data type for individual columns.
|
||||||
|
*
|
||||||
|
* If `schema` is provided then this property is ignored.
|
||||||
|
*/
|
||||||
|
dictionaryEncodeStrings: boolean = false
|
||||||
|
|
||||||
constructor (values?: Partial<MakeArrowTableOptions>) {
|
constructor (values?: Partial<MakeArrowTableOptions>) {
|
||||||
Object.assign(this, values)
|
Object.assign(this, values)
|
||||||
}
|
}
|
||||||
@@ -62,8 +101,29 @@ export class MakeArrowTableOptions {
|
|||||||
* An enhanced version of the {@link makeTable} function from Apache Arrow
|
* An enhanced version of the {@link makeTable} function from Apache Arrow
|
||||||
* that supports nested fields and embeddings columns.
|
* that supports nested fields and embeddings columns.
|
||||||
*
|
*
|
||||||
|
* This function converts an array of Record<String, any> (row-major JS objects)
|
||||||
|
* to an Arrow Table (a columnar structure)
|
||||||
|
*
|
||||||
* Note that it currently does not support nulls.
|
* Note that it currently does not support nulls.
|
||||||
*
|
*
|
||||||
|
* If a schema is provided then it will be used to determine the resulting array
|
||||||
|
* types. Fields will also be reordered to fit the order defined by the schema.
|
||||||
|
*
|
||||||
|
* If a schema is not provided then the types will be inferred and the field order
|
||||||
|
* will be controlled by the order of properties in the first record.
|
||||||
|
*
|
||||||
|
* If the input is empty then a schema must be provided to create an empty table.
|
||||||
|
*
|
||||||
|
* When a schema is not specified then data types will be inferred. The inference
|
||||||
|
* rules are as follows:
|
||||||
|
*
|
||||||
|
* - boolean => Bool
|
||||||
|
* - number => Float64
|
||||||
|
* - String => Utf8
|
||||||
|
* - Buffer => Binary
|
||||||
|
* - Record<String, any> => Struct
|
||||||
|
* - Array<any> => List
|
||||||
|
*
|
||||||
* @param data input data
|
* @param data input data
|
||||||
* @param options options to control the makeArrowTable call.
|
* @param options options to control the makeArrowTable call.
|
||||||
*
|
*
|
||||||
@@ -86,8 +146,10 @@ export class MakeArrowTableOptions {
|
|||||||
* ], { schema });
|
* ], { schema });
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
* It guesses the vector columns if the schema is not provided. For example,
|
* By default it assumes that the column named `vector` is a vector column
|
||||||
* by default it assumes that the column named `vector` is a vector column.
|
* and it will be converted into a fixed size list array of type float32.
|
||||||
|
* The `vectorColumns` option can be used to support other vector column
|
||||||
|
* names and data types.
|
||||||
*
|
*
|
||||||
* ```ts
|
* ```ts
|
||||||
*
|
*
|
||||||
@@ -134,211 +196,304 @@ export function makeArrowTable (
|
|||||||
data: Array<Record<string, any>>,
|
data: Array<Record<string, any>>,
|
||||||
options?: Partial<MakeArrowTableOptions>
|
options?: Partial<MakeArrowTableOptions>
|
||||||
): ArrowTable {
|
): ArrowTable {
|
||||||
if (data.length === 0) {
|
if (data.length === 0 && (options?.schema === undefined || options?.schema === null)) {
|
||||||
throw new Error('At least one record needs to be provided')
|
throw new Error('At least one record or a schema needs to be provided')
|
||||||
}
|
}
|
||||||
|
|
||||||
const opt = new MakeArrowTableOptions(options !== undefined ? options : {})
|
const opt = new MakeArrowTableOptions(options !== undefined ? options : {})
|
||||||
const columns: Record<string, Vector> = {}
|
const columns: Record<string, Vector> = {}
|
||||||
// TODO: sample dataset to find missing columns
|
// TODO: sample dataset to find missing columns
|
||||||
const columnNames = Object.keys(data[0])
|
// Prefer the field ordering of the schema, if present
|
||||||
|
const columnNames = ((options?.schema) != null) ? (options?.schema?.names as string[]) : Object.keys(data[0])
|
||||||
for (const colName of columnNames) {
|
for (const colName of columnNames) {
|
||||||
const values = data.map((datum) => datum[colName])
|
if (data.length !== 0 && !Object.prototype.hasOwnProperty.call(data[0], colName)) {
|
||||||
let vector: Vector
|
// The field is present in the schema, but not in the data, skip it
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Extract a single column from the records (transpose from row-major to col-major)
|
||||||
|
let values = data.map((datum) => datum[colName])
|
||||||
|
|
||||||
|
// By default (type === undefined) arrow will infer the type from the JS type
|
||||||
|
let type
|
||||||
if (opt.schema !== undefined) {
|
if (opt.schema !== undefined) {
|
||||||
// Explicit schema is provided, highest priority
|
// If there is a schema provided, then use that for the type instead
|
||||||
vector = vectorFromArray(
|
type = opt.schema?.fields.filter((f) => f.name === colName)[0]?.type
|
||||||
values,
|
if (DataType.isInt(type) && type.bitWidth === 64) {
|
||||||
opt.schema?.fields.filter((f) => f.name === colName)[0]?.type
|
// wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
|
||||||
)
|
values = values.map((v) => {
|
||||||
|
if (v === null) {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return BigInt(v)
|
||||||
|
})
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Otherwise, check to see if this column is one of the vector columns
|
||||||
|
// defined by opt.vectorColumns and, if so, use the fixed size list type
|
||||||
const vectorColumnOptions = opt.vectorColumns[colName]
|
const vectorColumnOptions = opt.vectorColumns[colName]
|
||||||
if (vectorColumnOptions !== undefined) {
|
if (vectorColumnOptions !== undefined) {
|
||||||
const fslType = new FixedSizeList(
|
type = newVectorType(values[0].length, vectorColumnOptions.type)
|
||||||
values[0].length,
|
|
||||||
new Field('item', vectorColumnOptions.type, false)
|
|
||||||
)
|
|
||||||
vector = vectorFromArray(values, fslType)
|
|
||||||
} else {
|
|
||||||
// Normal case
|
|
||||||
vector = vectorFromArray(values)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
columns[colName] = vector
|
|
||||||
|
try {
|
||||||
|
// Convert an Array of JS values to an arrow vector
|
||||||
|
columns[colName] = makeVector(values, type, opt.dictionaryEncodeStrings)
|
||||||
|
} catch (error: unknown) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||||
|
throw Error(`Could not convert column "${colName}" to Arrow: ${error}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ArrowTable(columns)
|
if (opt.schema != null) {
|
||||||
|
// `new ArrowTable(columns)` infers a schema which may sometimes have
|
||||||
|
// incorrect nullability (it assumes nullable=true if there are 0 rows)
|
||||||
|
//
|
||||||
|
// `new ArrowTable(schema, columns)` will also fail because it will create a
|
||||||
|
// batch with an inferred schema and then complain that the batch schema
|
||||||
|
// does not match the provided schema.
|
||||||
|
//
|
||||||
|
// To work around this we first create a table with the wrong schema and
|
||||||
|
// then patch the schema of the batches so we can use
|
||||||
|
// `new ArrowTable(schema, batches)` which does not do any schema inference
|
||||||
|
const firstTable = new ArrowTable(columns)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
|
const batchesFixed = firstTable.batches.map(batch => new RecordBatch(opt.schema!, batch.data))
|
||||||
|
return new ArrowTable(opt.schema, batchesFixed)
|
||||||
|
} else {
|
||||||
|
return new ArrowTable(columns)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts an Array of records into an Arrow Table, optionally applying an embeddings function to it.
|
/**
|
||||||
|
* Create an empty Arrow table with the provided schema
|
||||||
|
*/
|
||||||
|
export function makeEmptyTable (schema: Schema): ArrowTable {
|
||||||
|
return makeArrowTable([], { schema })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to convert Array<Array<any>> to a variable sized list array
|
||||||
|
function makeListVector (lists: any[][]): Vector<any> {
|
||||||
|
if (lists.length === 0 || lists[0].length === 0) {
|
||||||
|
throw Error('Cannot infer list vector from empty array or empty list')
|
||||||
|
}
|
||||||
|
const sampleList = lists[0]
|
||||||
|
let inferredType
|
||||||
|
try {
|
||||||
|
const sampleVector = makeVector(sampleList)
|
||||||
|
inferredType = sampleVector.type
|
||||||
|
} catch (error: unknown) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||||
|
throw Error(`Cannot infer list vector. Cannot infer inner type: ${error}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const listBuilder = makeBuilder({
|
||||||
|
type: new List(new Field('item', inferredType, true))
|
||||||
|
})
|
||||||
|
for (const list of lists) {
|
||||||
|
listBuilder.append(list)
|
||||||
|
}
|
||||||
|
return listBuilder.finish().toVector()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to convert an Array of JS values to an Arrow Vector
|
||||||
|
function makeVector (values: any[], type?: DataType, stringAsDictionary?: boolean): Vector<any> {
|
||||||
|
if (type !== undefined) {
|
||||||
|
// No need for inference, let Arrow create it
|
||||||
|
return vectorFromArray(values, type)
|
||||||
|
}
|
||||||
|
if (values.length === 0) {
|
||||||
|
throw Error('makeVector requires at least one value or the type must be specfied')
|
||||||
|
}
|
||||||
|
const sampleValue = values.find(val => val !== null && val !== undefined)
|
||||||
|
if (sampleValue === undefined) {
|
||||||
|
throw Error('makeVector cannot infer the type if all values are null or undefined')
|
||||||
|
}
|
||||||
|
if (Array.isArray(sampleValue)) {
|
||||||
|
// Default Arrow inference doesn't handle list types
|
||||||
|
return makeListVector(values)
|
||||||
|
} else if (Buffer.isBuffer(sampleValue)) {
|
||||||
|
// Default Arrow inference doesn't handle Buffer
|
||||||
|
return vectorFromArray(values, new Binary())
|
||||||
|
} else if (!(stringAsDictionary ?? false) && (typeof sampleValue === 'string' || sampleValue instanceof String)) {
|
||||||
|
// If the type is string then don't use Arrow's default inference unless dictionaries are requested
|
||||||
|
// because it will always use dictionary encoding for strings
|
||||||
|
return vectorFromArray(values, new Utf8())
|
||||||
|
} else {
|
||||||
|
// Convert a JS array of values to an arrow vector
|
||||||
|
return vectorFromArray(values)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyEmbeddings<T> (table: ArrowTable, embeddings?: EmbeddingFunction<T>, schema?: Schema): Promise<ArrowTable> {
|
||||||
|
if (embeddings == null) {
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert from ArrowTable to Record<String, Vector>
|
||||||
|
const colEntries = [...Array(table.numCols).keys()].map((_, idx) => {
|
||||||
|
const name = table.schema.fields[idx].name
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
|
const vec = table.getChildAt(idx)!
|
||||||
|
return [name, vec]
|
||||||
|
})
|
||||||
|
const newColumns = Object.fromEntries(colEntries)
|
||||||
|
|
||||||
|
const sourceColumn = newColumns[embeddings.sourceColumn]
|
||||||
|
const destColumn = embeddings.destColumn ?? 'vector'
|
||||||
|
const innerDestType = embeddings.embeddingDataType ?? new Float32()
|
||||||
|
if (sourceColumn === undefined) {
|
||||||
|
throw new Error(`Cannot apply embedding function because the source column '${embeddings.sourceColumn}' was not present in the data`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.numRows === 0) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
|
||||||
|
// We have an empty table and it already has the embedding column so no work needs to be done
|
||||||
|
// Note: we don't return an error like we did below because this is a common occurrence. For example,
|
||||||
|
// if we call convertToTable with 0 records and a schema that includes the embedding
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
if (embeddings.embeddingDimension !== undefined) {
|
||||||
|
const destType = newVectorType(embeddings.embeddingDimension, innerDestType)
|
||||||
|
newColumns[destColumn] = makeVector([], destType)
|
||||||
|
} else if (schema != null) {
|
||||||
|
const destField = schema.fields.find(f => f.name === destColumn)
|
||||||
|
if (destField != null) {
|
||||||
|
newColumns[destColumn] = makeVector([], destField.type)
|
||||||
|
} else {
|
||||||
|
throw new Error(`Attempt to apply embeddings to an empty table failed because schema was missing embedding column '${destColumn}'`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error('Attempt to apply embeddings to an empty table when the embeddings function does not specify `embeddingDimension`')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(newColumns, destColumn)) {
|
||||||
|
throw new Error(`Attempt to apply embeddings to table failed because column ${destColumn} already existed`)
|
||||||
|
}
|
||||||
|
if (table.batches.length > 1) {
|
||||||
|
throw new Error('Internal error: `makeArrowTable` unexpectedly created a table with more than one batch')
|
||||||
|
}
|
||||||
|
const values = sourceColumn.toArray()
|
||||||
|
const vectors = await embeddings.embed(values as T[])
|
||||||
|
if (vectors.length !== values.length) {
|
||||||
|
throw new Error('Embedding function did not return an embedding for each input element')
|
||||||
|
}
|
||||||
|
const destType = newVectorType(vectors[0].length, innerDestType)
|
||||||
|
newColumns[destColumn] = makeVector(vectors, destType)
|
||||||
|
}
|
||||||
|
|
||||||
|
const newTable = new ArrowTable(newColumns)
|
||||||
|
if (schema != null) {
|
||||||
|
if (schema.fields.find(f => f.name === destColumn) === undefined) {
|
||||||
|
throw new Error(`When using embedding functions and specifying a schema the schema should include the embedding column but the column ${destColumn} was missing`)
|
||||||
|
}
|
||||||
|
return alignTable(newTable, schema)
|
||||||
|
}
|
||||||
|
return newTable
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert an Array of records into an Arrow Table, optionally applying an
|
||||||
|
* embeddings function to it.
|
||||||
|
*
|
||||||
|
* This function calls `makeArrowTable` first to create the Arrow Table.
|
||||||
|
* Any provided `makeTableOptions` (e.g. a schema) will be passed on to
|
||||||
|
* that call.
|
||||||
|
*
|
||||||
|
* The embedding function will be passed a column of values (based on the
|
||||||
|
* `sourceColumn` of the embedding function) and expects to receive back
|
||||||
|
* number[][] which will be converted into a fixed size list column. By
|
||||||
|
* default this will be a fixed size list of Float32 but that can be
|
||||||
|
* customized by the `embeddingDataType` property of the embedding function.
|
||||||
|
*
|
||||||
|
* If a schema is provided in `makeTableOptions` then it should include the
|
||||||
|
* embedding columns. If no schema is provded then embedding columns will
|
||||||
|
* be placed at the end of the table, after all of the input columns.
|
||||||
|
*/
|
||||||
export async function convertToTable<T> (
|
export async function convertToTable<T> (
|
||||||
data: Array<Record<string, unknown>>,
|
data: Array<Record<string, unknown>>,
|
||||||
embeddings?: EmbeddingFunction<T>
|
embeddings?: EmbeddingFunction<T>,
|
||||||
|
makeTableOptions?: Partial<MakeArrowTableOptions>
|
||||||
): Promise<ArrowTable> {
|
): Promise<ArrowTable> {
|
||||||
if (data.length === 0) {
|
const table = makeArrowTable(data, makeTableOptions)
|
||||||
throw new Error('At least one record needs to be provided')
|
return await applyEmbeddings(table, embeddings, makeTableOptions?.schema)
|
||||||
}
|
|
||||||
|
|
||||||
const columns = Object.keys(data[0])
|
|
||||||
const records: Record<string, Vector> = {}
|
|
||||||
|
|
||||||
for (const columnsKey of columns) {
|
|
||||||
if (columnsKey === 'vector') {
|
|
||||||
const vectorSize = (data[0].vector as any[]).length
|
|
||||||
const listBuilder = newVectorBuilder(vectorSize)
|
|
||||||
for (const datum of data) {
|
|
||||||
if ((datum[columnsKey] as any[]).length !== vectorSize) {
|
|
||||||
throw new Error(`Invalid vector size, expected ${vectorSize}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
listBuilder.append(datum[columnsKey])
|
|
||||||
}
|
|
||||||
records[columnsKey] = listBuilder.finish().toVector()
|
|
||||||
} else {
|
|
||||||
const values = []
|
|
||||||
for (const datum of data) {
|
|
||||||
values.push(datum[columnsKey])
|
|
||||||
}
|
|
||||||
|
|
||||||
if (columnsKey === embeddings?.sourceColumn) {
|
|
||||||
const vectors = await embeddings.embed(values as T[])
|
|
||||||
records.vector = vectorFromArray(
|
|
||||||
vectors,
|
|
||||||
newVectorType(vectors[0].length)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof values[0] === 'string') {
|
|
||||||
// `vectorFromArray` converts strings into dictionary vectors, forcing it back to a string column
|
|
||||||
records[columnsKey] = vectorFromArray(values, new Utf8())
|
|
||||||
} else if (Array.isArray(values[0])) {
|
|
||||||
const elementType = getElementType(values[0])
|
|
||||||
let innerType
|
|
||||||
if (elementType === 'string') {
|
|
||||||
innerType = new Utf8()
|
|
||||||
} else if (elementType === 'number') {
|
|
||||||
innerType = new Float64()
|
|
||||||
} else {
|
|
||||||
// TODO: pass in schema if it exists, else keep going to the next element
|
|
||||||
throw new Error(`Unsupported array element type ${elementType}`)
|
|
||||||
}
|
|
||||||
const listBuilder = makeBuilder({
|
|
||||||
type: new List(new Field('item', innerType, true))
|
|
||||||
})
|
|
||||||
for (const value of values) {
|
|
||||||
listBuilder.append(value)
|
|
||||||
}
|
|
||||||
records[columnsKey] = listBuilder.finish().toVector()
|
|
||||||
} else {
|
|
||||||
// TODO if this is a struct field then recursively align the subfields
|
|
||||||
records[columnsKey] = vectorFromArray(values)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ArrowTable(records)
|
|
||||||
}
|
|
||||||
|
|
||||||
function getElementType (arr: any[]): string {
|
|
||||||
if (arr.length === 0) {
|
|
||||||
return 'undefined'
|
|
||||||
}
|
|
||||||
|
|
||||||
return typeof arr[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Creates a new Arrow ListBuilder that stores a Vector column
|
|
||||||
function newVectorBuilder (dim: number): FixedSizeListBuilder<Float32> {
|
|
||||||
return makeBuilder({
|
|
||||||
type: newVectorType(dim)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creates the Arrow Type for a Vector column with dimension `dim`
|
// Creates the Arrow Type for a Vector column with dimension `dim`
|
||||||
function newVectorType (dim: number): FixedSizeList<Float32> {
|
function newVectorType <T extends Float> (dim: number, innerType: T): FixedSizeList<T> {
|
||||||
// Somewhere we always default to have the elements nullable, so we need to set it to true
|
// Somewhere we always default to have the elements nullable, so we need to set it to true
|
||||||
// otherwise we often get schema mismatches because the stored data always has schema with nullable elements
|
// otherwise we often get schema mismatches because the stored data always has schema with nullable elements
|
||||||
const children = new Field<Float32>('item', new Float32(), true)
|
const children = new Field<T>('item', innerType, true)
|
||||||
return new FixedSizeList(dim, children)
|
return new FixedSizeList(dim, children)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts an Array of records into Arrow IPC format
|
/**
|
||||||
|
* Serialize an Array of records into a buffer using the Arrow IPC File serialization
|
||||||
|
*
|
||||||
|
* This function will call `convertToTable` and pass on `embeddings` and `schema`
|
||||||
|
*
|
||||||
|
* `schema` is required if data is empty
|
||||||
|
*/
|
||||||
export async function fromRecordsToBuffer<T> (
|
export async function fromRecordsToBuffer<T> (
|
||||||
data: Array<Record<string, unknown>>,
|
data: Array<Record<string, unknown>>,
|
||||||
embeddings?: EmbeddingFunction<T>,
|
embeddings?: EmbeddingFunction<T>,
|
||||||
schema?: Schema
|
schema?: Schema
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
let table = await convertToTable(data, embeddings)
|
const table = await convertToTable(data, embeddings, { schema })
|
||||||
if (schema !== undefined) {
|
|
||||||
table = alignTable(table, schema)
|
|
||||||
}
|
|
||||||
const writer = RecordBatchFileWriter.writeAll(table)
|
const writer = RecordBatchFileWriter.writeAll(table)
|
||||||
return Buffer.from(await writer.toUint8Array())
|
return Buffer.from(await writer.toUint8Array())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts an Array of records into Arrow IPC stream format
|
/**
|
||||||
|
* Serialize an Array of records into a buffer using the Arrow IPC Stream serialization
|
||||||
|
*
|
||||||
|
* This function will call `convertToTable` and pass on `embeddings` and `schema`
|
||||||
|
*
|
||||||
|
* `schema` is required if data is empty
|
||||||
|
*/
|
||||||
export async function fromRecordsToStreamBuffer<T> (
|
export async function fromRecordsToStreamBuffer<T> (
|
||||||
data: Array<Record<string, unknown>>,
|
data: Array<Record<string, unknown>>,
|
||||||
embeddings?: EmbeddingFunction<T>,
|
embeddings?: EmbeddingFunction<T>,
|
||||||
schema?: Schema
|
schema?: Schema
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
let table = await convertToTable(data, embeddings)
|
const table = await convertToTable(data, embeddings, { schema })
|
||||||
if (schema !== undefined) {
|
|
||||||
table = alignTable(table, schema)
|
|
||||||
}
|
|
||||||
const writer = RecordBatchStreamWriter.writeAll(table)
|
const writer = RecordBatchStreamWriter.writeAll(table)
|
||||||
return Buffer.from(await writer.toUint8Array())
|
return Buffer.from(await writer.toUint8Array())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts an Arrow Table into Arrow IPC format
|
/**
|
||||||
|
* Serialize an Arrow Table into a buffer using the Arrow IPC File serialization
|
||||||
|
*
|
||||||
|
* This function will apply `embeddings` to the table in a manner similar to
|
||||||
|
* `convertToTable`.
|
||||||
|
*
|
||||||
|
* `schema` is required if the table is empty
|
||||||
|
*/
|
||||||
export async function fromTableToBuffer<T> (
|
export async function fromTableToBuffer<T> (
|
||||||
table: ArrowTable,
|
table: ArrowTable,
|
||||||
embeddings?: EmbeddingFunction<T>,
|
embeddings?: EmbeddingFunction<T>,
|
||||||
schema?: Schema
|
schema?: Schema
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
if (embeddings !== undefined) {
|
const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema)
|
||||||
const source = table.getChild(embeddings.sourceColumn)
|
const writer = RecordBatchFileWriter.writeAll(tableWithEmbeddings)
|
||||||
|
|
||||||
if (source === null) {
|
|
||||||
throw new Error(
|
|
||||||
`The embedding source column ${embeddings.sourceColumn} was not found in the Arrow Table`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const vectors = await embeddings.embed(source.toArray() as T[])
|
|
||||||
const column = vectorFromArray(vectors, newVectorType(vectors[0].length))
|
|
||||||
table = table.assign(new ArrowTable({ vector: column }))
|
|
||||||
}
|
|
||||||
if (schema !== undefined) {
|
|
||||||
table = alignTable(table, schema)
|
|
||||||
}
|
|
||||||
const writer = RecordBatchFileWriter.writeAll(table)
|
|
||||||
return Buffer.from(await writer.toUint8Array())
|
return Buffer.from(await writer.toUint8Array())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts an Arrow Table into Arrow IPC stream format
|
/**
|
||||||
|
* Serialize an Arrow Table into a buffer using the Arrow IPC Stream serialization
|
||||||
|
*
|
||||||
|
* This function will apply `embeddings` to the table in a manner similar to
|
||||||
|
* `convertToTable`.
|
||||||
|
*
|
||||||
|
* `schema` is required if the table is empty
|
||||||
|
*/
|
||||||
export async function fromTableToStreamBuffer<T> (
|
export async function fromTableToStreamBuffer<T> (
|
||||||
table: ArrowTable,
|
table: ArrowTable,
|
||||||
embeddings?: EmbeddingFunction<T>,
|
embeddings?: EmbeddingFunction<T>,
|
||||||
schema?: Schema
|
schema?: Schema
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
if (embeddings !== undefined) {
|
const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema)
|
||||||
const source = table.getChild(embeddings.sourceColumn)
|
const writer = RecordBatchStreamWriter.writeAll(tableWithEmbeddings)
|
||||||
|
|
||||||
if (source === null) {
|
|
||||||
throw new Error(
|
|
||||||
`The embedding source column ${embeddings.sourceColumn} was not found in the Arrow Table`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const vectors = await embeddings.embed(source.toArray() as T[])
|
|
||||||
const column = vectorFromArray(vectors, newVectorType(vectors[0].length))
|
|
||||||
table = table.assign(new ArrowTable({ vector: column }))
|
|
||||||
}
|
|
||||||
if (schema !== undefined) {
|
|
||||||
table = alignTable(table, schema)
|
|
||||||
}
|
|
||||||
const writer = RecordBatchStreamWriter.writeAll(table)
|
|
||||||
return Buffer.from(await writer.toUint8Array())
|
return Buffer.from(await writer.toUint8Array())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,18 +12,53 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
|
import { type Float } from 'apache-arrow'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An embedding function that automatically creates vector representation for a given column.
|
* An embedding function that automatically creates vector representation for a given column.
|
||||||
*/
|
*/
|
||||||
export interface EmbeddingFunction<T> {
|
export interface EmbeddingFunction<T> {
|
||||||
/**
|
/**
|
||||||
* The name of the column that will be used as input for the Embedding Function.
|
* The name of the column that will be used as input for the Embedding Function.
|
||||||
*/
|
*/
|
||||||
sourceColumn: string
|
sourceColumn: string
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a vector representation for the given values.
|
* The data type of the embedding
|
||||||
*/
|
*
|
||||||
|
* The embedding function should return `number`. This will be converted into
|
||||||
|
* an Arrow float array. By default this will be Float32 but this property can
|
||||||
|
* be used to control the conversion.
|
||||||
|
*/
|
||||||
|
embeddingDataType?: Float
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The dimension of the embedding
|
||||||
|
*
|
||||||
|
* This is optional, normally this can be determined by looking at the results of
|
||||||
|
* `embed`. If this is not specified, and there is an attempt to apply the embedding
|
||||||
|
* to an empty table, then that process will fail.
|
||||||
|
*/
|
||||||
|
embeddingDimension?: number
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The name of the column that will contain the embedding
|
||||||
|
*
|
||||||
|
* By default this is "vector"
|
||||||
|
*/
|
||||||
|
destColumn?: string
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Should the source column be excluded from the resulting table
|
||||||
|
*
|
||||||
|
* By default the source column is included. Set this to true and
|
||||||
|
* only the embedding will be stored.
|
||||||
|
*/
|
||||||
|
excludeSource?: boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a vector representation for the given values.
|
||||||
|
*/
|
||||||
embed: (data: T[]) => Promise<number[][]>
|
embed: (data: T[]) => Promise<number[][]>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ const {
|
|||||||
export { Query }
|
export { Query }
|
||||||
export type { EmbeddingFunction }
|
export type { EmbeddingFunction }
|
||||||
export { OpenAIEmbeddingFunction } from './embedding/openai'
|
export { OpenAIEmbeddingFunction } from './embedding/openai'
|
||||||
export { makeArrowTable, type MakeArrowTableOptions } from './arrow'
|
export { convertToTable, makeArrowTable, type MakeArrowTableOptions } from './arrow'
|
||||||
|
|
||||||
const defaultAwsRegion = 'us-west-2'
|
const defaultAwsRegion = 'us-west-2'
|
||||||
|
|
||||||
|
|||||||
@@ -13,9 +13,10 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
import { describe } from 'mocha'
|
import { describe } from 'mocha'
|
||||||
import { assert } from 'chai'
|
import { assert, expect, use as chaiUse } from 'chai'
|
||||||
|
import * as chaiAsPromised from 'chai-as-promised'
|
||||||
|
|
||||||
import { fromTableToBuffer, makeArrowTable } from '../arrow'
|
import { convertToTable, fromTableToBuffer, makeArrowTable, makeEmptyTable } from '../arrow'
|
||||||
import {
|
import {
|
||||||
Field,
|
Field,
|
||||||
FixedSizeList,
|
FixedSizeList,
|
||||||
@@ -24,21 +25,79 @@ import {
|
|||||||
Int32,
|
Int32,
|
||||||
tableFromIPC,
|
tableFromIPC,
|
||||||
Schema,
|
Schema,
|
||||||
Float64
|
Float64,
|
||||||
|
type Table,
|
||||||
|
Binary,
|
||||||
|
Bool,
|
||||||
|
Utf8,
|
||||||
|
Struct,
|
||||||
|
List,
|
||||||
|
DataType,
|
||||||
|
Dictionary,
|
||||||
|
Int64
|
||||||
} from 'apache-arrow'
|
} from 'apache-arrow'
|
||||||
|
import { type EmbeddingFunction } from '../embedding/embedding_function'
|
||||||
|
|
||||||
describe('Apache Arrow tables', function () {
|
chaiUse(chaiAsPromised)
|
||||||
it('customized schema', async function () {
|
|
||||||
|
function sampleRecords (): Array<Record<string, any>> {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
binary: Buffer.alloc(5),
|
||||||
|
boolean: false,
|
||||||
|
number: 7,
|
||||||
|
string: 'hello',
|
||||||
|
struct: { x: 0, y: 0 },
|
||||||
|
list: ['anime', 'action', 'comedy']
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper method to verify various ways to create a table
|
||||||
|
async function checkTableCreation (tableCreationMethod: (records: any, recordsReversed: any, schema: Schema) => Promise<Table>): Promise<void> {
|
||||||
|
const records = sampleRecords()
|
||||||
|
const recordsReversed = [{
|
||||||
|
list: ['anime', 'action', 'comedy'],
|
||||||
|
struct: { x: 0, y: 0 },
|
||||||
|
string: 'hello',
|
||||||
|
number: 7,
|
||||||
|
boolean: false,
|
||||||
|
binary: Buffer.alloc(5)
|
||||||
|
}]
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field('binary', new Binary(), false),
|
||||||
|
new Field('boolean', new Bool(), false),
|
||||||
|
new Field('number', new Float64(), false),
|
||||||
|
new Field('string', new Utf8(), false),
|
||||||
|
new Field('struct', new Struct([
|
||||||
|
new Field('x', new Float64(), false),
|
||||||
|
new Field('y', new Float64(), false)
|
||||||
|
])),
|
||||||
|
new Field('list', new List(new Field('item', new Utf8(), false)), false)
|
||||||
|
])
|
||||||
|
|
||||||
|
const table = await tableCreationMethod(records, recordsReversed, schema)
|
||||||
|
schema.fields.forEach((field, idx) => {
|
||||||
|
const actualField = table.schema.fields[idx]
|
||||||
|
assert.isFalse(actualField.nullable)
|
||||||
|
assert.equal(table.getChild(field.name)?.type.toString(), field.type.toString())
|
||||||
|
assert.equal(table.getChildAt(idx)?.type.toString(), field.type.toString())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('The function makeArrowTable', function () {
|
||||||
|
it('will use data types from a provided schema instead of inference', async function () {
|
||||||
const schema = new Schema([
|
const schema = new Schema([
|
||||||
new Field('a', new Int32()),
|
new Field('a', new Int32()),
|
||||||
new Field('b', new Float32()),
|
new Field('b', new Float32()),
|
||||||
new Field('c', new FixedSizeList(3, new Field('item', new Float16())))
|
new Field('c', new FixedSizeList(3, new Field('item', new Float16()))),
|
||||||
|
new Field('d', new Int64())
|
||||||
])
|
])
|
||||||
const table = makeArrowTable(
|
const table = makeArrowTable(
|
||||||
[
|
[
|
||||||
{ a: 1, b: 2, c: [1, 2, 3] },
|
{ a: 1, b: 2, c: [1, 2, 3], d: 9 },
|
||||||
{ a: 4, b: 5, c: [4, 5, 6] },
|
{ a: 4, b: 5, c: [4, 5, 6], d: 10 },
|
||||||
{ a: 7, b: 8, c: [7, 8, 9] }
|
{ a: 7, b: 8, c: [7, 8, 9], d: null }
|
||||||
],
|
],
|
||||||
{ schema }
|
{ schema }
|
||||||
)
|
)
|
||||||
@@ -52,13 +111,13 @@ describe('Apache Arrow tables', function () {
|
|||||||
assert.deepEqual(actualSchema, schema)
|
assert.deepEqual(actualSchema, schema)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('default vector column', async function () {
|
it('will assume the column `vector` is FixedSizeList<Float32> by default', async function () {
|
||||||
const schema = new Schema([
|
const schema = new Schema([
|
||||||
new Field('a', new Float64()),
|
new Field('a', new Float64()),
|
||||||
new Field('b', new Float64()),
|
new Field('b', new Float64()),
|
||||||
new Field(
|
new Field(
|
||||||
'vector',
|
'vector',
|
||||||
new FixedSizeList(3, new Field('item', new Float32()))
|
new FixedSizeList(3, new Field('item', new Float32(), true))
|
||||||
)
|
)
|
||||||
])
|
])
|
||||||
const table = makeArrowTable([
|
const table = makeArrowTable([
|
||||||
@@ -76,12 +135,12 @@ describe('Apache Arrow tables', function () {
|
|||||||
assert.deepEqual(actualSchema, schema)
|
assert.deepEqual(actualSchema, schema)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('2 vector columns', async function () {
|
it('can support multiple vector columns', async function () {
|
||||||
const schema = new Schema([
|
const schema = new Schema([
|
||||||
new Field('a', new Float64()),
|
new Field('a', new Float64()),
|
||||||
new Field('b', new Float64()),
|
new Field('b', new Float64()),
|
||||||
new Field('vec1', new FixedSizeList(3, new Field('item', new Float16()))),
|
new Field('vec1', new FixedSizeList(3, new Field('item', new Float16(), true))),
|
||||||
new Field('vec2', new FixedSizeList(3, new Field('item', new Float16())))
|
new Field('vec2', new FixedSizeList(3, new Field('item', new Float16(), true)))
|
||||||
])
|
])
|
||||||
const table = makeArrowTable(
|
const table = makeArrowTable(
|
||||||
[
|
[
|
||||||
@@ -105,4 +164,157 @@ describe('Apache Arrow tables', function () {
|
|||||||
const actualSchema = actual.schema
|
const actualSchema = actual.schema
|
||||||
assert.deepEqual(actualSchema, schema)
|
assert.deepEqual(actualSchema, schema)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('will allow different vector column types', async function () {
|
||||||
|
const table = makeArrowTable(
|
||||||
|
[
|
||||||
|
{ fp16: [1], fp32: [1], fp64: [1] }
|
||||||
|
],
|
||||||
|
{
|
||||||
|
vectorColumns: {
|
||||||
|
fp16: { type: new Float16() },
|
||||||
|
fp32: { type: new Float32() },
|
||||||
|
fp64: { type: new Float64() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.equal(table.getChild('fp16')?.type.children[0].type.toString(), new Float16().toString())
|
||||||
|
assert.equal(table.getChild('fp32')?.type.children[0].type.toString(), new Float32().toString())
|
||||||
|
assert.equal(table.getChild('fp64')?.type.children[0].type.toString(), new Float64().toString())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will use dictionary encoded strings if asked', async function () {
|
||||||
|
const table = makeArrowTable([{ str: 'hello' }])
|
||||||
|
assert.isTrue(DataType.isUtf8(table.getChild('str')?.type))
|
||||||
|
|
||||||
|
const tableWithDict = makeArrowTable([{ str: 'hello' }], { dictionaryEncodeStrings: true })
|
||||||
|
assert.isTrue(DataType.isDictionary(tableWithDict.getChild('str')?.type))
|
||||||
|
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field('str', new Dictionary(new Utf8(), new Int32()))
|
||||||
|
])
|
||||||
|
|
||||||
|
const tableWithDict2 = makeArrowTable([{ str: 'hello' }], { schema })
|
||||||
|
assert.isTrue(DataType.isDictionary(tableWithDict2.getChild('str')?.type))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will infer data types correctly', async function () {
|
||||||
|
await checkTableCreation(async (records) => makeArrowTable(records))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will allow a schema to be provided', async function () {
|
||||||
|
await checkTableCreation(async (records, _, schema) => makeArrowTable(records, { schema }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will use the field order of any provided schema', async function () {
|
||||||
|
await checkTableCreation(async (_, recordsReversed, schema) => makeArrowTable(recordsReversed, { schema }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will make an empty table', async function () {
|
||||||
|
await checkTableCreation(async (_, __, schema) => makeArrowTable([], { schema }))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
class DummyEmbedding implements EmbeddingFunction<string> {
|
||||||
|
public readonly sourceColumn = 'string'
|
||||||
|
public readonly embeddingDimension = 2
|
||||||
|
public readonly embeddingDataType = new Float16()
|
||||||
|
|
||||||
|
async embed (data: string[]): Promise<number[][]> {
|
||||||
|
return data.map(
|
||||||
|
() => [0.0, 0.0]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class DummyEmbeddingWithNoDimension implements EmbeddingFunction<string> {
|
||||||
|
public readonly sourceColumn = 'string'
|
||||||
|
|
||||||
|
async embed (data: string[]): Promise<number[][]> {
|
||||||
|
return data.map(
|
||||||
|
() => [0.0, 0.0]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('convertToTable', function () {
|
||||||
|
it('will infer data types correctly', async function () {
|
||||||
|
await checkTableCreation(async (records) => await convertToTable(records))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will allow a schema to be provided', async function () {
|
||||||
|
await checkTableCreation(async (records, _, schema) => await convertToTable(records, undefined, { schema }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will use the field order of any provided schema', async function () {
|
||||||
|
await checkTableCreation(async (_, recordsReversed, schema) => await convertToTable(recordsReversed, undefined, { schema }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will make an empty table', async function () {
|
||||||
|
await checkTableCreation(async (_, __, schema) => await convertToTable([], undefined, { schema }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will apply embeddings', async function () {
|
||||||
|
const records = sampleRecords()
|
||||||
|
const table = await convertToTable(records, new DummyEmbedding())
|
||||||
|
assert.isTrue(DataType.isFixedSizeList(table.getChild('vector')?.type))
|
||||||
|
assert.equal(table.getChild('vector')?.type.children[0].type.toString(), new Float16().toString())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will fail if missing the embedding source column', async function () {
|
||||||
|
return await expect(convertToTable([{ id: 1 }], new DummyEmbedding())).to.be.rejectedWith("'string' was not present")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('use embeddingDimension if embedding missing from table', async function () {
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field('string', new Utf8(), false)
|
||||||
|
])
|
||||||
|
// Simulate getting an empty Arrow table (minus embedding) from some other source
|
||||||
|
// In other words, we aren't starting with records
|
||||||
|
const table = makeEmptyTable(schema)
|
||||||
|
|
||||||
|
// If the embedding specifies the dimension we are fine
|
||||||
|
await fromTableToBuffer(table, new DummyEmbedding())
|
||||||
|
|
||||||
|
// We can also supply a schema and should be ok
|
||||||
|
const schemaWithEmbedding = new Schema([
|
||||||
|
new Field('string', new Utf8(), false),
|
||||||
|
new Field('vector', new FixedSizeList(2, new Field('item', new Float16(), false)), false)
|
||||||
|
])
|
||||||
|
await fromTableToBuffer(table, new DummyEmbeddingWithNoDimension(), schemaWithEmbedding)
|
||||||
|
|
||||||
|
// Otherwise we will get an error
|
||||||
|
return await expect(fromTableToBuffer(table, new DummyEmbeddingWithNoDimension())).to.be.rejectedWith('does not specify `embeddingDimension`')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will apply embeddings to an empty table', async function () {
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field('string', new Utf8(), false),
|
||||||
|
new Field('vector', new FixedSizeList(2, new Field('item', new Float16(), false)), false)
|
||||||
|
])
|
||||||
|
const table = await convertToTable([], new DummyEmbedding(), { schema })
|
||||||
|
assert.isTrue(DataType.isFixedSizeList(table.getChild('vector')?.type))
|
||||||
|
assert.equal(table.getChild('vector')?.type.children[0].type.toString(), new Float16().toString())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will complain if embeddings present but schema missing embedding column', async function () {
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field('string', new Utf8(), false)
|
||||||
|
])
|
||||||
|
return await expect(convertToTable([], new DummyEmbedding(), { schema })).to.be.rejectedWith('column vector was missing')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('will provide a nice error if run twice', async function () {
|
||||||
|
const records = sampleRecords()
|
||||||
|
const table = await convertToTable(records, new DummyEmbedding())
|
||||||
|
// fromTableToBuffer will try and apply the embeddings again
|
||||||
|
return await expect(fromTableToBuffer(table, new DummyEmbedding())).to.be.rejectedWith('already existed')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('makeEmptyTable', function () {
|
||||||
|
it('will make an empty table', async function () {
|
||||||
|
await checkTableCreation(async (_, __, schema) => makeEmptyTable(schema))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,6 +9,6 @@
|
|||||||
"declaration": true,
|
"declaration": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
// "esModuleInterop": true,
|
"sourceMap": true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,5 +23,8 @@ napi = { version = "2.15", default-features = false, features = [
|
|||||||
] }
|
] }
|
||||||
napi-derive = "2"
|
napi-derive = "2"
|
||||||
|
|
||||||
|
# Prevent dynamic linking of lzma, which comes from datafusion
|
||||||
|
lzma-sys = { version = "*", features = ["static"] }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
napi-build = "2.1"
|
napi-build = "2.1"
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
|
|
||||||
import { makeArrowTable, toBuffer } from "../vectordb/arrow";
|
import { makeArrowTable, toBuffer } from "../vectordb/arrow";
|
||||||
import {
|
import {
|
||||||
|
Int64,
|
||||||
Field,
|
Field,
|
||||||
FixedSizeList,
|
FixedSizeList,
|
||||||
Float16,
|
Float16,
|
||||||
@@ -104,3 +105,16 @@ test("2 vector columns", function () {
|
|||||||
const actualSchema = actual.schema;
|
const actualSchema = actual.schema;
|
||||||
expect(actualSchema.toString()).toEqual(schema.toString());
|
expect(actualSchema.toString()).toEqual(schema.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("handles int64", function() {
|
||||||
|
// https://github.com/lancedb/lancedb/issues/960
|
||||||
|
const schema = new Schema([
|
||||||
|
new Field("x", new Int64(), true)
|
||||||
|
]);
|
||||||
|
const table = makeArrowTable([
|
||||||
|
{ x: 1 },
|
||||||
|
{ x: 2 },
|
||||||
|
{ x: 3 }
|
||||||
|
], { schema });
|
||||||
|
expect(table.schema).toEqual(schema);
|
||||||
|
})
|
||||||
@@ -13,6 +13,7 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
Int64,
|
||||||
Field,
|
Field,
|
||||||
FixedSizeList,
|
FixedSizeList,
|
||||||
Float,
|
Float,
|
||||||
@@ -23,6 +24,7 @@ import {
|
|||||||
Vector,
|
Vector,
|
||||||
vectorFromArray,
|
vectorFromArray,
|
||||||
tableToIPC,
|
tableToIPC,
|
||||||
|
DataType,
|
||||||
} from "apache-arrow";
|
} from "apache-arrow";
|
||||||
|
|
||||||
/** Data type accepted by NodeJS SDK */
|
/** Data type accepted by NodeJS SDK */
|
||||||
@@ -137,15 +139,18 @@ export function makeArrowTable(
|
|||||||
const columnNames = Object.keys(data[0]);
|
const columnNames = Object.keys(data[0]);
|
||||||
for (const colName of columnNames) {
|
for (const colName of columnNames) {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||||
const values = data.map((datum) => datum[colName]);
|
let values = data.map((datum) => datum[colName]);
|
||||||
let vector: Vector;
|
let vector: Vector;
|
||||||
|
|
||||||
if (opt.schema !== undefined) {
|
if (opt.schema !== undefined) {
|
||||||
// Explicit schema is provided, highest priority
|
// Explicit schema is provided, highest priority
|
||||||
vector = vectorFromArray(
|
const fieldType: DataType | undefined = opt.schema.fields.filter((f) => f.name === colName)[0]?.type as DataType;
|
||||||
values,
|
if (fieldType instanceof Int64) {
|
||||||
opt.schema?.fields.filter((f) => f.name === colName)[0]?.type
|
// wrap in BigInt to avoid bug: https://github.com/apache/arrow/issues/40051
|
||||||
);
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||||
|
values = values.map((v) => BigInt(v));
|
||||||
|
}
|
||||||
|
vector = vectorFromArray(values, fieldType);
|
||||||
} else {
|
} else {
|
||||||
const vectorColumnOptions = opt.vectorColumns[colName];
|
const vectorColumnOptions = opt.vectorColumns[colName];
|
||||||
if (vectorColumnOptions !== undefined) {
|
if (vectorColumnOptions !== undefined) {
|
||||||
|
|||||||
2
nodejs/vectordb/native.d.ts
vendored
2
nodejs/vectordb/native.d.ts
vendored
@@ -73,7 +73,7 @@ export class Table {
|
|||||||
/** Return Schema as empty Arrow IPC file. */
|
/** Return Schema as empty Arrow IPC file. */
|
||||||
schema(): Buffer
|
schema(): Buffer
|
||||||
add(buf: Buffer): Promise<void>
|
add(buf: Buffer): Promise<void>
|
||||||
countRows(filter?: string): Promise<bigint>
|
countRows(filter?: string | undefined | null): Promise<bigint>
|
||||||
delete(predicate: string): Promise<void>
|
delete(predicate: string): Promise<void>
|
||||||
createIndex(): IndexBuilder
|
createIndex(): IndexBuilder
|
||||||
query(): Query
|
query(): Query
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 0.5.4
|
current_version = 0.5.6
|
||||||
commit = True
|
commit = True
|
||||||
message = [python] Bump version: {current_version} → {new_version}
|
message = [python] Bump version: {current_version} → {new_version}
|
||||||
tag = True
|
tag = True
|
||||||
|
|||||||
@@ -13,8 +13,9 @@
|
|||||||
|
|
||||||
import importlib.metadata
|
import importlib.metadata
|
||||||
import os
|
import os
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from typing import Optional
|
from typing import Optional, Union
|
||||||
|
|
||||||
__version__ = importlib.metadata.version("lancedb")
|
__version__ = importlib.metadata.version("lancedb")
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ def connect(
|
|||||||
region: str = "us-east-1",
|
region: str = "us-east-1",
|
||||||
host_override: Optional[str] = None,
|
host_override: Optional[str] = None,
|
||||||
read_consistency_interval: Optional[timedelta] = None,
|
read_consistency_interval: Optional[timedelta] = None,
|
||||||
|
request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
|
||||||
) -> DBConnection:
|
) -> DBConnection:
|
||||||
"""Connect to a LanceDB database.
|
"""Connect to a LanceDB database.
|
||||||
|
|
||||||
@@ -58,7 +60,14 @@ def connect(
|
|||||||
the last check, then the table will be checked for updates. Note: this
|
the last check, then the table will be checked for updates. Note: this
|
||||||
consistency only applies to read operations. Write operations are
|
consistency only applies to read operations. Write operations are
|
||||||
always consistent.
|
always consistent.
|
||||||
|
request_thread_pool: int or ThreadPoolExecutor, optional
|
||||||
|
The thread pool to use for making batch requests to the LanceDB Cloud API.
|
||||||
|
If an integer, then a ThreadPoolExecutor will be created with that
|
||||||
|
number of threads. If None, then a ThreadPoolExecutor will be created
|
||||||
|
with the default number of threads. If a ThreadPoolExecutor, then that
|
||||||
|
executor will be used for making requests. This is for LanceDB Cloud
|
||||||
|
only and is only used when making batch requests (i.e., passing in
|
||||||
|
multiple queries to the search method at once).
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
@@ -86,5 +95,9 @@ def connect(
|
|||||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||||
if api_key is None:
|
if api_key is None:
|
||||||
raise ValueError(f"api_key is required to connected LanceDB cloud: {uri}")
|
raise ValueError(f"api_key is required to connected LanceDB cloud: {uri}")
|
||||||
return RemoteDBConnection(uri, api_key, region, host_override)
|
if isinstance(request_thread_pool, int):
|
||||||
|
request_thread_pool = ThreadPoolExecutor(request_thread_pool)
|
||||||
|
return RemoteDBConnection(
|
||||||
|
uri, api_key, region, host_override, request_thread_pool=request_thread_pool
|
||||||
|
)
|
||||||
return LanceDBConnection(uri, read_consistency_interval=read_consistency_interval)
|
return LanceDBConnection(uri, read_consistency_interval=read_consistency_interval)
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
import importlib
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import List, Union
|
from typing import List, Union
|
||||||
|
|
||||||
@@ -91,25 +90,6 @@ class EmbeddingFunction(BaseModel, ABC):
|
|||||||
texts = texts.combine_chunks().to_pylist()
|
texts = texts.combine_chunks().to_pylist()
|
||||||
return texts
|
return texts
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def safe_import(cls, module: str, mitigation=None):
|
|
||||||
"""
|
|
||||||
Import the specified module. If the module is not installed,
|
|
||||||
raise an ImportError with a helpful message.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
module : str
|
|
||||||
The name of the module to import
|
|
||||||
mitigation : Optional[str]
|
|
||||||
The package(s) to install to mitigate the error.
|
|
||||||
If not provided then the module name will be used.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return importlib.import_module(module)
|
|
||||||
except ImportError:
|
|
||||||
raise ImportError(f"Please install {mitigation or module}")
|
|
||||||
|
|
||||||
def safe_model_dump(self):
|
def safe_model_dump(self):
|
||||||
from ..pydantic import PYDANTIC_VERSION
|
from ..pydantic import PYDANTIC_VERSION
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import numpy as np
|
|||||||
|
|
||||||
from lancedb.pydantic import PYDANTIC_VERSION
|
from lancedb.pydantic import PYDANTIC_VERSION
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import TEXT
|
from .utils import TEXT
|
||||||
@@ -183,8 +184,8 @@ class BedRockText(TextEmbeddingFunction):
|
|||||||
boto3.client
|
boto3.client
|
||||||
The boto3 client for Amazon Bedrock service
|
The boto3 client for Amazon Bedrock service
|
||||||
"""
|
"""
|
||||||
botocore = self.safe_import("botocore")
|
botocore = attempt_import_or_raise("botocore")
|
||||||
boto3 = self.safe_import("boto3")
|
boto3 = attempt_import_or_raise("boto3")
|
||||||
|
|
||||||
session_kwargs = {"region_name": self.region}
|
session_kwargs = {"region_name": self.region}
|
||||||
client_kwargs = {**session_kwargs}
|
client_kwargs = {**session_kwargs}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from typing import ClassVar, List, Union
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import api_key_not_found_help
|
from .utils import api_key_not_found_help
|
||||||
@@ -84,7 +85,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
|||||||
return [emb for emb in rs.embeddings]
|
return [emb for emb in rs.embeddings]
|
||||||
|
|
||||||
def _init_client(self):
|
def _init_client(self):
|
||||||
cohere = self.safe_import("cohere")
|
cohere = attempt_import_or_raise("cohere")
|
||||||
if CohereEmbeddingFunction.client is None:
|
if CohereEmbeddingFunction.client is None:
|
||||||
if os.environ.get("COHERE_API_KEY") is None:
|
if os.environ.get("COHERE_API_KEY") is None:
|
||||||
api_key_not_found_help("cohere")
|
api_key_not_found_help("cohere")
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import numpy as np
|
|||||||
|
|
||||||
from lancedb.pydantic import PYDANTIC_VERSION
|
from lancedb.pydantic import PYDANTIC_VERSION
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import TEXT, api_key_not_found_help
|
from .utils import TEXT, api_key_not_found_help
|
||||||
@@ -134,7 +135,7 @@ class GeminiText(TextEmbeddingFunction):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def client(self):
|
def client(self):
|
||||||
genai = self.safe_import("google.generativeai", "google.generativeai")
|
genai = attempt_import_or_raise("google.generativeai", "google.generativeai")
|
||||||
|
|
||||||
if not os.environ.get("GOOGLE_API_KEY"):
|
if not os.environ.get("GOOGLE_API_KEY"):
|
||||||
api_key_not_found_help("google")
|
api_key_not_found_help("google")
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from typing import List, Union
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import weak_lru
|
from .utils import weak_lru
|
||||||
@@ -122,7 +123,7 @@ class GteEmbeddings(TextEmbeddingFunction):
|
|||||||
|
|
||||||
return Model()
|
return Model()
|
||||||
else:
|
else:
|
||||||
sentence_transformers = self.safe_import(
|
sentence_transformers = attempt_import_or_raise(
|
||||||
"sentence_transformers", "sentence-transformers"
|
"sentence_transformers", "sentence-transformers"
|
||||||
)
|
)
|
||||||
return sentence_transformers.SentenceTransformer(
|
return sentence_transformers.SentenceTransformer(
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from typing import List
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import TEXT, weak_lru
|
from .utils import TEXT, weak_lru
|
||||||
@@ -102,9 +103,9 @@ class InstructorEmbeddingFunction(TextEmbeddingFunction):
|
|||||||
# convert_to_numpy: bool = True # Hardcoding this as numpy can be ingested directly
|
# convert_to_numpy: bool = True # Hardcoding this as numpy can be ingested directly
|
||||||
|
|
||||||
source_instruction: str = "represent the document for retrieval"
|
source_instruction: str = "represent the document for retrieval"
|
||||||
query_instruction: str = (
|
query_instruction: (
|
||||||
"represent the document for retrieving the most similar documents"
|
str
|
||||||
)
|
) = "represent the document for retrieving the most similar documents"
|
||||||
|
|
||||||
@weak_lru(maxsize=1)
|
@weak_lru(maxsize=1)
|
||||||
def ndims(self):
|
def ndims(self):
|
||||||
@@ -131,10 +132,10 @@ class InstructorEmbeddingFunction(TextEmbeddingFunction):
|
|||||||
|
|
||||||
@weak_lru(maxsize=1)
|
@weak_lru(maxsize=1)
|
||||||
def get_model(self):
|
def get_model(self):
|
||||||
instructor_embedding = self.safe_import(
|
instructor_embedding = attempt_import_or_raise(
|
||||||
"InstructorEmbedding", "InstructorEmbedding"
|
"InstructorEmbedding", "InstructorEmbedding"
|
||||||
)
|
)
|
||||||
torch = self.safe_import("torch", "torch")
|
torch = attempt_import_or_raise("torch", "torch")
|
||||||
|
|
||||||
model = instructor_embedding.INSTRUCTOR(self.name)
|
model = instructor_embedding.INSTRUCTOR(self.name)
|
||||||
if self.quantize:
|
if self.quantize:
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import pyarrow as pa
|
|||||||
from pydantic import PrivateAttr
|
from pydantic import PrivateAttr
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import EmbeddingFunction
|
from .base import EmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import IMAGES, url_retrieve
|
from .utils import IMAGES, url_retrieve
|
||||||
@@ -50,7 +51,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
open_clip = self.safe_import("open_clip", "open-clip")
|
open_clip = attempt_import_or_raise("open_clip", "open-clip")
|
||||||
model, _, preprocess = open_clip.create_model_and_transforms(
|
model, _, preprocess = open_clip.create_model_and_transforms(
|
||||||
self.name, pretrained=self.pretrained
|
self.name, pretrained=self.pretrained
|
||||||
)
|
)
|
||||||
@@ -78,14 +79,14 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
if isinstance(query, str):
|
if isinstance(query, str):
|
||||||
return [self.generate_text_embeddings(query)]
|
return [self.generate_text_embeddings(query)]
|
||||||
else:
|
else:
|
||||||
PIL = self.safe_import("PIL", "pillow")
|
PIL = attempt_import_or_raise("PIL", "pillow")
|
||||||
if isinstance(query, PIL.Image.Image):
|
if isinstance(query, PIL.Image.Image):
|
||||||
return [self.generate_image_embedding(query)]
|
return [self.generate_image_embedding(query)]
|
||||||
else:
|
else:
|
||||||
raise TypeError("OpenClip supports str or PIL Image as query")
|
raise TypeError("OpenClip supports str or PIL Image as query")
|
||||||
|
|
||||||
def generate_text_embeddings(self, text: str) -> np.ndarray:
|
def generate_text_embeddings(self, text: str) -> np.ndarray:
|
||||||
torch = self.safe_import("torch")
|
torch = attempt_import_or_raise("torch")
|
||||||
text = self.sanitize_input(text)
|
text = self.sanitize_input(text)
|
||||||
text = self._tokenizer(text)
|
text = self._tokenizer(text)
|
||||||
text.to(self.device)
|
text.to(self.device)
|
||||||
@@ -144,7 +145,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
The image to embed. If the image is a str, it is treated as a uri.
|
The image to embed. If the image is a str, it is treated as a uri.
|
||||||
If the image is bytes, it is treated as the raw image bytes.
|
If the image is bytes, it is treated as the raw image bytes.
|
||||||
"""
|
"""
|
||||||
torch = self.safe_import("torch")
|
torch = attempt_import_or_raise("torch")
|
||||||
# TODO handle retry and errors for https
|
# TODO handle retry and errors for https
|
||||||
image = self._to_pil(image)
|
image = self._to_pil(image)
|
||||||
image = self._preprocess(image).unsqueeze(0)
|
image = self._preprocess(image).unsqueeze(0)
|
||||||
@@ -152,7 +153,7 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
|||||||
return self._encode_and_normalize_image(image)
|
return self._encode_and_normalize_image(image)
|
||||||
|
|
||||||
def _to_pil(self, image: Union[str, bytes]):
|
def _to_pil(self, image: Union[str, bytes]):
|
||||||
PIL = self.safe_import("PIL", "pillow")
|
PIL = attempt_import_or_raise("PIL", "pillow")
|
||||||
if isinstance(image, bytes):
|
if isinstance(image, bytes):
|
||||||
return PIL.Image.open(io.BytesIO(image))
|
return PIL.Image.open(io.BytesIO(image))
|
||||||
if isinstance(image, PIL.Image.Image):
|
if isinstance(image, PIL.Image.Image):
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from typing import List, Optional, Union
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import api_key_not_found_help
|
from .utils import api_key_not_found_help
|
||||||
@@ -68,7 +69,7 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def _openai_client(self):
|
def _openai_client(self):
|
||||||
openai = self.safe_import("openai")
|
openai = attempt_import_or_raise("openai")
|
||||||
|
|
||||||
if not os.environ.get("OPENAI_API_KEY"):
|
if not os.environ.get("OPENAI_API_KEY"):
|
||||||
api_key_not_found_help("openai")
|
api_key_not_found_help("openai")
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from typing import List, Union
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
from ..util import attempt_import_or_raise
|
||||||
from .base import TextEmbeddingFunction
|
from .base import TextEmbeddingFunction
|
||||||
from .registry import register
|
from .registry import register
|
||||||
from .utils import weak_lru
|
from .utils import weak_lru
|
||||||
@@ -75,7 +76,7 @@ class SentenceTransformerEmbeddings(TextEmbeddingFunction):
|
|||||||
|
|
||||||
TODO: use lru_cache instead with a reasonable/configurable maxsize
|
TODO: use lru_cache instead with a reasonable/configurable maxsize
|
||||||
"""
|
"""
|
||||||
sentence_transformers = self.safe_import(
|
sentence_transformers = attempt_import_or_raise(
|
||||||
"sentence_transformers", "sentence-transformers"
|
"sentence_transformers", "sentence-transformers"
|
||||||
)
|
)
|
||||||
return sentence_transformers.SentenceTransformer(self.name, device=self.device)
|
return sentence_transformers.SentenceTransformer(self.name, device=self.device)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import pyarrow as pa
|
|||||||
from lance.vector import vec_to_table
|
from lance.vector import vec_to_table
|
||||||
from retry import retry
|
from retry import retry
|
||||||
|
|
||||||
from ..util import safe_import_pandas
|
from ..util import deprecated, safe_import_pandas
|
||||||
from ..utils.general import LOGGER
|
from ..utils.general import LOGGER
|
||||||
|
|
||||||
pd = safe_import_pandas()
|
pd = safe_import_pandas()
|
||||||
@@ -38,6 +38,7 @@ IMAGES = Union[
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@deprecated
|
||||||
def with_embeddings(
|
def with_embeddings(
|
||||||
func: Callable,
|
func: Callable,
|
||||||
data: DATA,
|
data: DATA,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import pyarrow as pa
|
|||||||
import pydantic
|
import pydantic
|
||||||
|
|
||||||
from . import __version__
|
from . import __version__
|
||||||
from .common import VEC, VECTOR_COLUMN_NAME
|
from .common import VEC
|
||||||
from .rerankers.base import Reranker
|
from .rerankers.base import Reranker
|
||||||
from .rerankers.linear_combination import LinearCombinationReranker
|
from .rerankers.linear_combination import LinearCombinationReranker
|
||||||
from .util import safe_import_pandas
|
from .util import safe_import_pandas
|
||||||
@@ -75,7 +75,7 @@ class Query(pydantic.BaseModel):
|
|||||||
tuning advice.
|
tuning advice.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
vector_column: str = VECTOR_COLUMN_NAME
|
vector_column: Optional[str] = None
|
||||||
|
|
||||||
# vector to search for
|
# vector to search for
|
||||||
vector: Union[List[float], List[List[float]]]
|
vector: Union[List[float], List[List[float]]]
|
||||||
@@ -403,7 +403,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
|||||||
self,
|
self,
|
||||||
table: "Table",
|
table: "Table",
|
||||||
query: Union[np.ndarray, list, "PIL.Image.Image"],
|
query: Union[np.ndarray, list, "PIL.Image.Image"],
|
||||||
vector_column: str = VECTOR_COLUMN_NAME,
|
vector_column: str,
|
||||||
):
|
):
|
||||||
super().__init__(table)
|
super().__init__(table)
|
||||||
self._query = query
|
self._query = query
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
import inspect
|
import inspect
|
||||||
import logging
|
import logging
|
||||||
import uuid
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from typing import Iterable, List, Optional, Union
|
from typing import Iterable, List, Optional, Union
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
@@ -39,6 +40,7 @@ class RemoteDBConnection(DBConnection):
|
|||||||
api_key: str,
|
api_key: str,
|
||||||
region: str,
|
region: str,
|
||||||
host_override: Optional[str] = None,
|
host_override: Optional[str] = None,
|
||||||
|
request_thread_pool: Optional[ThreadPoolExecutor] = None,
|
||||||
):
|
):
|
||||||
"""Connect to a remote LanceDB database."""
|
"""Connect to a remote LanceDB database."""
|
||||||
parsed = urlparse(db_url)
|
parsed = urlparse(db_url)
|
||||||
@@ -49,6 +51,7 @@ class RemoteDBConnection(DBConnection):
|
|||||||
self._client = RestfulLanceDBClient(
|
self._client = RestfulLanceDBClient(
|
||||||
self.db_name, region, api_key, host_override
|
self.db_name, region, api_key, host_override
|
||||||
)
|
)
|
||||||
|
self._request_thread_pool = request_thread_pool
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
return f"RemoteConnect(name={self.db_name})"
|
return f"RemoteConnect(name={self.db_name})"
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import uuid
|
import uuid
|
||||||
|
from concurrent.futures import Future
|
||||||
from functools import cached_property
|
from functools import cached_property
|
||||||
from typing import Dict, Optional, Union
|
from typing import Dict, Optional, Union
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ from lancedb.merge import LanceMergeInsertBuilder
|
|||||||
|
|
||||||
from ..query import LanceVectorQueryBuilder
|
from ..query import LanceVectorQueryBuilder
|
||||||
from ..table import Query, Table, _sanitize_data
|
from ..table import Query, Table, _sanitize_data
|
||||||
from ..util import value_to_sql
|
from ..util import inf_vector_column_query, value_to_sql
|
||||||
from .arrow import to_ipc_binary
|
from .arrow import to_ipc_binary
|
||||||
from .client import ARROW_STREAM_CONTENT_TYPE
|
from .client import ARROW_STREAM_CONTENT_TYPE
|
||||||
from .db import RemoteDBConnection
|
from .db import RemoteDBConnection
|
||||||
@@ -198,7 +199,9 @@ class RemoteTable(Table):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def search(
|
def search(
|
||||||
self, query: Union[VEC, str], vector_column_name: str = VECTOR_COLUMN_NAME
|
self,
|
||||||
|
query: Union[VEC, str],
|
||||||
|
vector_column_name: Optional[str] = None,
|
||||||
) -> LanceVectorQueryBuilder:
|
) -> LanceVectorQueryBuilder:
|
||||||
"""Create a search query to find the nearest neighbors
|
"""Create a search query to find the nearest neighbors
|
||||||
of the given query vector. We currently support [vector search][search]
|
of the given query vector. We currently support [vector search][search]
|
||||||
@@ -217,7 +220,7 @@ class RemoteTable(Table):
|
|||||||
... ]
|
... ]
|
||||||
>>> table = db.create_table("my_table", data) # doctest: +SKIP
|
>>> table = db.create_table("my_table", data) # doctest: +SKIP
|
||||||
>>> query = [0.4, 1.4, 2.4]
|
>>> query = [0.4, 1.4, 2.4]
|
||||||
>>> (table.search(query, vector_column_name="vector") # doctest: +SKIP
|
>>> (table.search(query) # doctest: +SKIP
|
||||||
... .where("original_width > 1000", prefilter=True) # doctest: +SKIP
|
... .where("original_width > 1000", prefilter=True) # doctest: +SKIP
|
||||||
... .select(["caption", "original_width"]) # doctest: +SKIP
|
... .select(["caption", "original_width"]) # doctest: +SKIP
|
||||||
... .limit(2) # doctest: +SKIP
|
... .limit(2) # doctest: +SKIP
|
||||||
@@ -236,9 +239,14 @@ class RemoteTable(Table):
|
|||||||
|
|
||||||
- If None then the select/where/limit clauses are applied to filter
|
- If None then the select/where/limit clauses are applied to filter
|
||||||
the table
|
the table
|
||||||
vector_column_name: str
|
vector_column_name: str, optional
|
||||||
The name of the vector column to search.
|
The name of the vector column to search.
|
||||||
*default "vector"*
|
|
||||||
|
- If not specified then the vector column is inferred from
|
||||||
|
the table schema
|
||||||
|
|
||||||
|
- If the table has multiple vector columns then the *vector_column_name*
|
||||||
|
needs to be specified. Otherwise, an error is raised.
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
@@ -253,6 +261,8 @@ class RemoteTable(Table):
|
|||||||
- and also the "_distance" column which is the distance between the query
|
- and also the "_distance" column which is the distance between the query
|
||||||
vector and the returned vector.
|
vector and the returned vector.
|
||||||
"""
|
"""
|
||||||
|
if vector_column_name is None:
|
||||||
|
vector_column_name = inf_vector_column_query(self.schema)
|
||||||
return LanceVectorQueryBuilder(self, query, vector_column_name)
|
return LanceVectorQueryBuilder(self, query, vector_column_name)
|
||||||
|
|
||||||
def _execute_query(self, query: Query) -> pa.Table:
|
def _execute_query(self, query: Query) -> pa.Table:
|
||||||
@@ -261,15 +271,28 @@ class RemoteTable(Table):
|
|||||||
and len(query.vector) > 0
|
and len(query.vector) > 0
|
||||||
and not isinstance(query.vector[0], float)
|
and not isinstance(query.vector[0], float)
|
||||||
):
|
):
|
||||||
|
if self._conn._request_thread_pool is None:
|
||||||
|
|
||||||
|
def submit(name, q):
|
||||||
|
f = Future()
|
||||||
|
f.set_result(self._conn._client.query(name, q))
|
||||||
|
return f
|
||||||
|
else:
|
||||||
|
|
||||||
|
def submit(name, q):
|
||||||
|
return self._conn._request_thread_pool.submit(
|
||||||
|
self._conn._client.query, name, q
|
||||||
|
)
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
for v in query.vector:
|
for v in query.vector:
|
||||||
v = list(v)
|
v = list(v)
|
||||||
q = query.copy()
|
q = query.copy()
|
||||||
q.vector = v
|
q.vector = v
|
||||||
results.append(self._conn._client.query(self._name, q))
|
results.append(submit(self._name, q))
|
||||||
|
|
||||||
return pa.concat_tables(
|
return pa.concat_tables(
|
||||||
[add_index(r.to_arrow(), i) for i, r in enumerate(results)]
|
[add_index(r.result().to_arrow(), i) for i, r in enumerate(results)]
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
result = self._conn._client.query(self._name, query)
|
result = self._conn._client.query(self._name, query)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Union
|
|||||||
|
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from ..util import safe_import
|
from ..util import attempt_import_or_raise
|
||||||
from .base import Reranker
|
from .base import Reranker
|
||||||
|
|
||||||
|
|
||||||
@@ -41,7 +41,7 @@ class CohereReranker(Reranker):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def _client(self):
|
def _client(self):
|
||||||
cohere = safe_import("cohere")
|
cohere = attempt_import_or_raise("cohere")
|
||||||
if os.environ.get("COHERE_API_KEY") is None and self.api_key is None:
|
if os.environ.get("COHERE_API_KEY") is None and self.api_key is None:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"COHERE_API_KEY not set. Either set it in your environment or \
|
"COHERE_API_KEY not set. Either set it in your environment or \
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from functools import cached_property
|
|||||||
|
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from ..util import safe_import
|
from ..util import attempt_import_or_raise
|
||||||
from .base import Reranker
|
from .base import Reranker
|
||||||
|
|
||||||
|
|
||||||
@@ -29,7 +29,9 @@ class ColbertReranker(Reranker):
|
|||||||
super().__init__(return_score)
|
super().__init__(return_score)
|
||||||
self.model_name = model_name
|
self.model_name = model_name
|
||||||
self.column = column
|
self.column = column
|
||||||
self.torch = safe_import("torch") # import here for faster ops later
|
self.torch = attempt_import_or_raise(
|
||||||
|
"torch"
|
||||||
|
) # import here for faster ops later
|
||||||
|
|
||||||
def rerank_hybrid(
|
def rerank_hybrid(
|
||||||
self,
|
self,
|
||||||
@@ -80,7 +82,7 @@ class ColbertReranker(Reranker):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def _model(self):
|
def _model(self):
|
||||||
transformers = safe_import("transformers")
|
transformers = attempt_import_or_raise("transformers")
|
||||||
tokenizer = transformers.AutoTokenizer.from_pretrained(self.model_name)
|
tokenizer = transformers.AutoTokenizer.from_pretrained(self.model_name)
|
||||||
model = transformers.AutoModel.from_pretrained(self.model_name)
|
model = transformers.AutoModel.from_pretrained(self.model_name)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from typing import Union
|
|||||||
|
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from ..util import safe_import
|
from ..util import attempt_import_or_raise
|
||||||
from .base import Reranker
|
from .base import Reranker
|
||||||
|
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ class CrossEncoderReranker(Reranker):
|
|||||||
return_score="relevance",
|
return_score="relevance",
|
||||||
):
|
):
|
||||||
super().__init__(return_score)
|
super().__init__(return_score)
|
||||||
torch = safe_import("torch")
|
torch = attempt_import_or_raise("torch")
|
||||||
self.model_name = model_name
|
self.model_name = model_name
|
||||||
self.column = column
|
self.column = column
|
||||||
self.device = device
|
self.device = device
|
||||||
@@ -41,7 +41,7 @@ class CrossEncoderReranker(Reranker):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def model(self):
|
def model(self):
|
||||||
sbert = safe_import("sentence_transformers")
|
sbert = attempt_import_or_raise("sentence_transformers")
|
||||||
cross_encoder = sbert.CrossEncoder(self.model_name)
|
cross_encoder = sbert.CrossEncoder(self.model_name)
|
||||||
|
|
||||||
return cross_encoder
|
return cross_encoder
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from typing import Optional
|
|||||||
|
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from ..util import safe_import
|
from ..util import attempt_import_or_raise
|
||||||
from .base import Reranker
|
from .base import Reranker
|
||||||
|
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ class OpenaiReranker(Reranker):
|
|||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
model_name : str, default "gpt-3.5-turbo-1106 "
|
model_name : str, default "gpt-4-turbo-preview"
|
||||||
The name of the cross encoder model to use.
|
The name of the cross encoder model to use.
|
||||||
column : str, default "text"
|
column : str, default "text"
|
||||||
The name of the column to use as input to the cross encoder model.
|
The name of the column to use as input to the cross encoder model.
|
||||||
@@ -29,7 +29,7 @@ class OpenaiReranker(Reranker):
|
|||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
model_name: str = "gpt-3.5-turbo-1106",
|
model_name: str = "gpt-4-turbo-preview",
|
||||||
column: str = "text",
|
column: str = "text",
|
||||||
return_score="relevance",
|
return_score="relevance",
|
||||||
api_key: Optional[str] = None,
|
api_key: Optional[str] = None,
|
||||||
@@ -93,7 +93,9 @@ class OpenaiReranker(Reranker):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def _client(self):
|
def _client(self):
|
||||||
openai = safe_import("openai") # TODO: force version or handle versions < 1.0
|
openai = attempt_import_or_raise(
|
||||||
|
"openai"
|
||||||
|
) # TODO: force version or handle versions < 1.0
|
||||||
if os.environ.get("OPENAI_API_KEY") is None and self.api_key is None:
|
if os.environ.get("OPENAI_API_KEY") is None and self.api_key is None:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"OPENAI_API_KEY not set. Either set it in your environment or \
|
"OPENAI_API_KEY not set. Either set it in your environment or \
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ from .pydantic import LanceModel, model_to_dict
|
|||||||
from .query import LanceQueryBuilder, Query
|
from .query import LanceQueryBuilder, Query
|
||||||
from .util import (
|
from .util import (
|
||||||
fs_from_uri,
|
fs_from_uri,
|
||||||
|
inf_vector_column_query,
|
||||||
join_uri,
|
join_uri,
|
||||||
safe_import_pandas,
|
safe_import_pandas,
|
||||||
safe_import_polars,
|
safe_import_polars,
|
||||||
@@ -413,7 +414,7 @@ class Table(ABC):
|
|||||||
def search(
|
def search(
|
||||||
self,
|
self,
|
||||||
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple]] = None,
|
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple]] = None,
|
||||||
vector_column_name: str = VECTOR_COLUMN_NAME,
|
vector_column_name: Optional[str] = None,
|
||||||
query_type: str = "auto",
|
query_type: str = "auto",
|
||||||
) -> LanceQueryBuilder:
|
) -> LanceQueryBuilder:
|
||||||
"""Create a search query to find the nearest neighbors
|
"""Create a search query to find the nearest neighbors
|
||||||
@@ -433,7 +434,7 @@ class Table(ABC):
|
|||||||
... ]
|
... ]
|
||||||
>>> table = db.create_table("my_table", data)
|
>>> table = db.create_table("my_table", data)
|
||||||
>>> query = [0.4, 1.4, 2.4]
|
>>> query = [0.4, 1.4, 2.4]
|
||||||
>>> (table.search(query, vector_column_name="vector")
|
>>> (table.search(query)
|
||||||
... .where("original_width > 1000", prefilter=True)
|
... .where("original_width > 1000", prefilter=True)
|
||||||
... .select(["caption", "original_width"])
|
... .select(["caption", "original_width"])
|
||||||
... .limit(2)
|
... .limit(2)
|
||||||
@@ -452,11 +453,16 @@ class Table(ABC):
|
|||||||
|
|
||||||
- If None then the select/where/limit clauses are applied to filter
|
- If None then the select/where/limit clauses are applied to filter
|
||||||
the table
|
the table
|
||||||
vector_column_name: str
|
vector_column_name: str, optional
|
||||||
The name of the vector column to search.
|
The name of the vector column to search.
|
||||||
|
|
||||||
The vector column needs to be a pyarrow fixed size list type
|
The vector column needs to be a pyarrow fixed size list type
|
||||||
*default "vector"*
|
|
||||||
|
- If not specified then the vector column is inferred from
|
||||||
|
the table schema
|
||||||
|
|
||||||
|
- If the table has multiple vector columns then the *vector_column_name*
|
||||||
|
needs to be specified. Otherwise, an error is raised.
|
||||||
query_type: str
|
query_type: str
|
||||||
*default "auto"*.
|
*default "auto"*.
|
||||||
Acceptable types are: "vector", "fts", "hybrid", or "auto"
|
Acceptable types are: "vector", "fts", "hybrid", or "auto"
|
||||||
@@ -1193,7 +1199,7 @@ class LanceTable(Table):
|
|||||||
def search(
|
def search(
|
||||||
self,
|
self,
|
||||||
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple]] = None,
|
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple]] = None,
|
||||||
vector_column_name: str = VECTOR_COLUMN_NAME,
|
vector_column_name: Optional[str] = None,
|
||||||
query_type: str = "auto",
|
query_type: str = "auto",
|
||||||
) -> LanceQueryBuilder:
|
) -> LanceQueryBuilder:
|
||||||
"""Create a search query to find the nearest neighbors
|
"""Create a search query to find the nearest neighbors
|
||||||
@@ -1211,7 +1217,7 @@ class LanceTable(Table):
|
|||||||
... ]
|
... ]
|
||||||
>>> table = db.create_table("my_table", data)
|
>>> table = db.create_table("my_table", data)
|
||||||
>>> query = [0.4, 1.4, 2.4]
|
>>> query = [0.4, 1.4, 2.4]
|
||||||
>>> (table.search(query, vector_column_name="vector")
|
>>> (table.search(query)
|
||||||
... .where("original_width > 1000", prefilter=True)
|
... .where("original_width > 1000", prefilter=True)
|
||||||
... .select(["caption", "original_width"])
|
... .select(["caption", "original_width"])
|
||||||
... .limit(2)
|
... .limit(2)
|
||||||
@@ -1230,8 +1236,17 @@ class LanceTable(Table):
|
|||||||
|
|
||||||
- If None then the select/[where][sql]/limit clauses are applied
|
- If None then the select/[where][sql]/limit clauses are applied
|
||||||
to filter the table
|
to filter the table
|
||||||
vector_column_name: str, default "vector"
|
vector_column_name: str, optional
|
||||||
The name of the vector column to search.
|
The name of the vector column to search.
|
||||||
|
|
||||||
|
The vector column needs to be a pyarrow fixed size list type
|
||||||
|
*default "vector"*
|
||||||
|
|
||||||
|
- If not specified then the vector column is inferred from
|
||||||
|
the table schema
|
||||||
|
|
||||||
|
- If the table has multiple vector columns then the *vector_column_name*
|
||||||
|
needs to be specified. Otherwise, an error is raised.
|
||||||
query_type: str, default "auto"
|
query_type: str, default "auto"
|
||||||
"vector", "fts", or "auto"
|
"vector", "fts", or "auto"
|
||||||
If "auto" then the query type is inferred from the query;
|
If "auto" then the query type is inferred from the query;
|
||||||
@@ -1249,6 +1264,8 @@ class LanceTable(Table):
|
|||||||
and also the "_distance" column which is the distance between the query
|
and also the "_distance" column which is the distance between the query
|
||||||
vector and the returned vector.
|
vector and the returned vector.
|
||||||
"""
|
"""
|
||||||
|
if vector_column_name is None and query is not None:
|
||||||
|
vector_column_name = inf_vector_column_query(self.schema)
|
||||||
register_event("search_table")
|
register_event("search_table")
|
||||||
return LanceQueryBuilder.create(
|
return LanceQueryBuilder.create(
|
||||||
self, query, query_type, vector_column_name=vector_column_name
|
self, query, query_type, vector_column_name=vector_column_name
|
||||||
@@ -1435,6 +1452,7 @@ class LanceTable(Table):
|
|||||||
|
|
||||||
def _execute_query(self, query: Query) -> pa.Table:
|
def _execute_query(self, query: Query) -> pa.Table:
|
||||||
ds = self.to_lance()
|
ds = self.to_lance()
|
||||||
|
|
||||||
return ds.to_table(
|
return ds.to_table(
|
||||||
columns=query.columns,
|
columns=query.columns,
|
||||||
filter=query.filter,
|
filter=query.filter,
|
||||||
|
|||||||
@@ -11,15 +11,18 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
|
import functools
|
||||||
import importlib
|
import importlib
|
||||||
import os
|
import os
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import warnings
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from functools import singledispatch
|
from functools import singledispatch
|
||||||
from typing import Tuple, Union
|
from typing import Tuple, Union
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import pyarrow as pa
|
||||||
import pyarrow.fs as pa_fs
|
import pyarrow.fs as pa_fs
|
||||||
|
|
||||||
|
|
||||||
@@ -115,7 +118,7 @@ def join_uri(base: Union[str, pathlib.Path], *parts: str) -> str:
|
|||||||
return "/".join([p.rstrip("/") for p in [base, *parts]])
|
return "/".join([p.rstrip("/") for p in [base, *parts]])
|
||||||
|
|
||||||
|
|
||||||
def safe_import(module: str, mitigation=None):
|
def attempt_import_or_raise(module: str, mitigation=None):
|
||||||
"""
|
"""
|
||||||
Import the specified module. If the module is not installed,
|
Import the specified module. If the module is not installed,
|
||||||
raise an ImportError with a helpful message.
|
raise an ImportError with a helpful message.
|
||||||
@@ -152,6 +155,44 @@ def safe_import_polars():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def inf_vector_column_query(schema: pa.Schema) -> str:
|
||||||
|
"""
|
||||||
|
Get the vector column name
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
schema : pa.Schema
|
||||||
|
The schema of the vector column.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str: the vector column name.
|
||||||
|
"""
|
||||||
|
vector_col_name = ""
|
||||||
|
vector_col_count = 0
|
||||||
|
for field_name in schema.names:
|
||||||
|
field = schema.field(field_name)
|
||||||
|
if pa.types.is_fixed_size_list(field.type) and pa.types.is_floating(
|
||||||
|
field.type.value_type
|
||||||
|
):
|
||||||
|
vector_col_count += 1
|
||||||
|
if vector_col_count > 1:
|
||||||
|
raise ValueError(
|
||||||
|
"Schema has more than one vector column. "
|
||||||
|
"Please specify the vector column name "
|
||||||
|
"for vector search"
|
||||||
|
)
|
||||||
|
break
|
||||||
|
elif vector_col_count == 1:
|
||||||
|
vector_col_name = field_name
|
||||||
|
if vector_col_count == 0:
|
||||||
|
raise ValueError(
|
||||||
|
"There is no vector column in the data. "
|
||||||
|
"Please specify the vector column name for vector search"
|
||||||
|
)
|
||||||
|
return vector_col_name
|
||||||
|
|
||||||
|
|
||||||
@singledispatch
|
@singledispatch
|
||||||
def value_to_sql(value):
|
def value_to_sql(value):
|
||||||
raise NotImplementedError("SQL conversion is not implemented for this type")
|
raise NotImplementedError("SQL conversion is not implemented for this type")
|
||||||
@@ -200,3 +241,25 @@ def _(value: list):
|
|||||||
@value_to_sql.register(np.ndarray)
|
@value_to_sql.register(np.ndarray)
|
||||||
def _(value: np.ndarray):
|
def _(value: np.ndarray):
|
||||||
return value_to_sql(value.tolist())
|
return value_to_sql(value.tolist())
|
||||||
|
|
||||||
|
|
||||||
|
def deprecated(func):
|
||||||
|
"""This is a decorator which can be used to mark functions
|
||||||
|
as deprecated. It will result in a warning being emitted
|
||||||
|
when the function is used."""
|
||||||
|
|
||||||
|
@functools.wraps(func)
|
||||||
|
def new_func(*args, **kwargs):
|
||||||
|
warnings.simplefilter("always", DeprecationWarning) # turn off filter
|
||||||
|
warnings.warn(
|
||||||
|
(
|
||||||
|
f"Function {func.__name__} is deprecated and will be "
|
||||||
|
"removed in a future version"
|
||||||
|
),
|
||||||
|
category=DeprecationWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
warnings.simplefilter("default", DeprecationWarning) # reset filter
|
||||||
|
return func(*args, **kwargs)
|
||||||
|
|
||||||
|
return new_func
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "lancedb"
|
name = "lancedb"
|
||||||
version = "0.5.4"
|
version = "0.5.6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"deprecation",
|
"deprecation",
|
||||||
"pylance==0.9.15",
|
"pylance==0.9.16",
|
||||||
"ratelimiter~=1.0",
|
"ratelimiter~=1.0",
|
||||||
"retry>=0.9.2",
|
"retry>=0.9.2",
|
||||||
"tqdm>=4.27.0",
|
"tqdm>=4.27.0",
|
||||||
|
|||||||
@@ -69,10 +69,14 @@ def test_basic_text_embeddings(alias, tmp_path):
|
|||||||
)
|
)
|
||||||
|
|
||||||
query = "greetings"
|
query = "greetings"
|
||||||
actual = table.search(query).limit(1).to_pydantic(Words)[0]
|
actual = (
|
||||||
|
table.search(query, vector_column_name="vector").limit(1).to_pydantic(Words)[0]
|
||||||
|
)
|
||||||
|
|
||||||
vec = func.compute_query_embeddings(query)[0]
|
vec = func.compute_query_embeddings(query)[0]
|
||||||
expected = table.search(vec).limit(1).to_pydantic(Words)[0]
|
expected = (
|
||||||
|
table.search(vec, vector_column_name="vector").limit(1).to_pydantic(Words)[0]
|
||||||
|
)
|
||||||
assert actual.text == expected.text
|
assert actual.text == expected.text
|
||||||
assert actual.text == "hello world"
|
assert actual.text == "hello world"
|
||||||
assert not np.allclose(actual.vector, actual.vector2)
|
assert not np.allclose(actual.vector, actual.vector2)
|
||||||
@@ -116,7 +120,11 @@ def test_openclip(tmp_path):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# text search
|
# text search
|
||||||
actual = table.search("man's best friend").limit(1).to_pydantic(Images)[0]
|
actual = (
|
||||||
|
table.search("man's best friend", vector_column_name="vector")
|
||||||
|
.limit(1)
|
||||||
|
.to_pydantic(Images)[0]
|
||||||
|
)
|
||||||
assert actual.label == "dog"
|
assert actual.label == "dog"
|
||||||
frombytes = (
|
frombytes = (
|
||||||
table.search("man's best friend", vector_column_name="vec_from_bytes")
|
table.search("man's best friend", vector_column_name="vec_from_bytes")
|
||||||
@@ -130,7 +138,11 @@ def test_openclip(tmp_path):
|
|||||||
query_image_uri = "http://farm1.staticflickr.com/200/467715466_ed4a31801f_z.jpg"
|
query_image_uri = "http://farm1.staticflickr.com/200/467715466_ed4a31801f_z.jpg"
|
||||||
image_bytes = requests.get(query_image_uri).content
|
image_bytes = requests.get(query_image_uri).content
|
||||||
query_image = Image.open(io.BytesIO(image_bytes))
|
query_image = Image.open(io.BytesIO(image_bytes))
|
||||||
actual = table.search(query_image).limit(1).to_pydantic(Images)[0]
|
actual = (
|
||||||
|
table.search(query_image, vector_column_name="vector")
|
||||||
|
.limit(1)
|
||||||
|
.to_pydantic(Images)[0]
|
||||||
|
)
|
||||||
assert actual.label == "dog"
|
assert actual.label == "dog"
|
||||||
other = (
|
other = (
|
||||||
table.search(query_image, vector_column_name="vec_from_bytes")
|
table.search(query_image, vector_column_name="vec_from_bytes")
|
||||||
|
|||||||
@@ -38,4 +38,5 @@ def test_remote_db():
|
|||||||
setattr(conn, "_client", FakeLanceDBClient())
|
setattr(conn, "_client", FakeLanceDBClient())
|
||||||
|
|
||||||
table = conn["test"]
|
table = conn["test"]
|
||||||
|
table.schema = pa.schema([pa.field("vector", pa.list_(pa.float32(), 2))])
|
||||||
table.search([1.0, 2.0]).to_pandas()
|
table.search([1.0, 2.0]).to_pandas()
|
||||||
|
|||||||
@@ -710,6 +710,59 @@ def test_empty_query(db):
|
|||||||
assert len(df) == 100
|
assert len(df) == 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_with_schema_inf_single_vector(db):
|
||||||
|
class MyTable(LanceModel):
|
||||||
|
text: str
|
||||||
|
vector_col: Vector(10)
|
||||||
|
|
||||||
|
table = LanceTable.create(
|
||||||
|
db,
|
||||||
|
"my_table",
|
||||||
|
schema=MyTable,
|
||||||
|
)
|
||||||
|
|
||||||
|
v1 = np.random.randn(10)
|
||||||
|
v2 = np.random.randn(10)
|
||||||
|
data = [
|
||||||
|
{"vector_col": v1, "text": "foo"},
|
||||||
|
{"vector_col": v2, "text": "bar"},
|
||||||
|
]
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
table.add(df)
|
||||||
|
|
||||||
|
q = np.random.randn(10)
|
||||||
|
result1 = table.search(q, vector_column_name="vector_col").limit(1).to_pandas()
|
||||||
|
result2 = table.search(q).limit(1).to_pandas()
|
||||||
|
|
||||||
|
assert result1["text"].iloc[0] == result2["text"].iloc[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_with_schema_inf_multiple_vector(db):
|
||||||
|
class MyTable(LanceModel):
|
||||||
|
text: str
|
||||||
|
vector1: Vector(10)
|
||||||
|
vector2: Vector(10)
|
||||||
|
|
||||||
|
table = LanceTable.create(
|
||||||
|
db,
|
||||||
|
"my_table",
|
||||||
|
schema=MyTable,
|
||||||
|
)
|
||||||
|
|
||||||
|
v1 = np.random.randn(10)
|
||||||
|
v2 = np.random.randn(10)
|
||||||
|
data = [
|
||||||
|
{"vector1": v1, "vector2": v2, "text": "foo"},
|
||||||
|
{"vector1": v2, "vector2": v1, "text": "bar"},
|
||||||
|
]
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
table.add(df)
|
||||||
|
|
||||||
|
q = np.random.randn(10)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
table.search(q).limit(1).to_pandas()
|
||||||
|
|
||||||
|
|
||||||
def test_compact_cleanup(db):
|
def test_compact_cleanup(db):
|
||||||
table = LanceTable.create(
|
table = LanceTable.create(
|
||||||
db,
|
db,
|
||||||
@@ -750,10 +803,8 @@ def test_count_rows(db):
|
|||||||
assert table.count_rows(filter="text='bar'") == 1
|
assert table.count_rows(filter="text='bar'") == 1
|
||||||
|
|
||||||
|
|
||||||
def test_hybrid_search(db):
|
def test_hybrid_search(db, tmp_path):
|
||||||
# hardcoding temporarily.. this test is failing with tmp_path mockdb.
|
db = MockDB(str(tmp_path))
|
||||||
# Probably not being parsed right by the fts
|
|
||||||
db = MockDB("~/lancedb_")
|
|
||||||
# Create a LanceDB table schema with a vector and a text column
|
# Create a LanceDB table schema with a vector and a text column
|
||||||
emb = EmbeddingFunctionRegistry.get_instance().get("test")()
|
emb = EmbeddingFunctionRegistry.get_instance().get("test")()
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "vectordb-node"
|
name = "vectordb-node"
|
||||||
version = "0.4.8"
|
version = "0.4.10"
|
||||||
description = "Serverless, low-latency vector database for AI applications"
|
description = "Serverless, low-latency vector database for AI applications"
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
@@ -31,3 +31,6 @@ object_store = { workspace = true, features = ["aws"] }
|
|||||||
snafu = { workspace = true }
|
snafu = { workspace = true }
|
||||||
async-trait = "0"
|
async-trait = "0"
|
||||||
env_logger = "0"
|
env_logger = "0"
|
||||||
|
|
||||||
|
# Prevent dynamic linking of lzma, which comes from datafusion
|
||||||
|
lzma-sys = { version = "*", features = ["static"] }
|
||||||
|
|||||||
@@ -17,10 +17,7 @@ use neon::types::buffer::TypedArray;
|
|||||||
|
|
||||||
use crate::error::ResultExt;
|
use crate::error::ResultExt;
|
||||||
|
|
||||||
pub fn vec_str_to_array<'a, C: Context<'a>>(
|
pub fn vec_str_to_array<'a, C: Context<'a>>(vec: &[String], cx: &mut C) -> JsResult<'a, JsArray> {
|
||||||
vec: &Vec<String>,
|
|
||||||
cx: &mut C,
|
|
||||||
) -> JsResult<'a, JsArray> {
|
|
||||||
let a = JsArray::new(cx, vec.len() as u32);
|
let a = JsArray::new(cx, vec.len() as u32);
|
||||||
for (i, s) in vec.iter().enumerate() {
|
for (i, s) in vec.iter().enumerate() {
|
||||||
let v = cx.string(s);
|
let v = cx.string(s);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "vectordb"
|
name = "vectordb"
|
||||||
version = "0.4.8"
|
version = "0.4.10"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
description = "LanceDB: A serverless, low-latency vector database for AI applications"
|
description = "LanceDB: A serverless, low-latency vector database for AI applications"
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|||||||
@@ -422,13 +422,11 @@ mod tests {
|
|||||||
let tmp_dir = tempdir().unwrap();
|
let tmp_dir = tempdir().unwrap();
|
||||||
let uri = std::fs::canonicalize(tmp_dir.path().to_str().unwrap()).unwrap();
|
let uri = std::fs::canonicalize(tmp_dir.path().to_str().unwrap()).unwrap();
|
||||||
|
|
||||||
let mut relative_anacestors = vec![];
|
|
||||||
let current_dir = std::env::current_dir().unwrap();
|
let current_dir = std::env::current_dir().unwrap();
|
||||||
let mut ancestors = current_dir.ancestors();
|
let ancestors = current_dir.ancestors();
|
||||||
while let Some(_) = ancestors.next() {
|
let relative_ancestors = vec![".."; ancestors.count()];
|
||||||
relative_anacestors.push("..");
|
|
||||||
}
|
let relative_root = std::path::PathBuf::from(relative_ancestors.join("/"));
|
||||||
let relative_root = std::path::PathBuf::from(relative_anacestors.join("/"));
|
|
||||||
let relative_uri = relative_root.join(&uri);
|
let relative_uri = relative_root.join(&uri);
|
||||||
|
|
||||||
let db = Database::connect(relative_uri.to_str().unwrap())
|
let db = Database::connect(relative_uri.to_str().unwrap())
|
||||||
|
|||||||
@@ -357,12 +357,14 @@ mod test {
|
|||||||
let db = Database::connect(dir1.to_str().unwrap()).await.unwrap();
|
let db = Database::connect(dir1.to_str().unwrap()).await.unwrap();
|
||||||
|
|
||||||
let mut param = WriteParams::default();
|
let mut param = WriteParams::default();
|
||||||
let mut store_params = ObjectStoreParams::default();
|
let store_params = ObjectStoreParams {
|
||||||
store_params.object_store_wrapper = Some(object_store_wrapper);
|
object_store_wrapper: Some(object_store_wrapper),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
param.store_params = Some(store_params);
|
param.store_params = Some(store_params);
|
||||||
|
|
||||||
let mut datagen = BatchGenerator::new();
|
let mut datagen = BatchGenerator::new();
|
||||||
datagen = datagen.col(Box::new(IncrementingInt32::default()));
|
datagen = datagen.col(Box::<IncrementingInt32>::default());
|
||||||
datagen = datagen.col(Box::new(RandomVector::default().named("vector".into())));
|
datagen = datagen.col(Box::new(RandomVector::default().named("vector".into())));
|
||||||
|
|
||||||
let res = db
|
let res = db
|
||||||
|
|||||||
@@ -257,7 +257,7 @@ mod tests {
|
|||||||
assert_eq!(query.query_vector.unwrap(), new_vector);
|
assert_eq!(query.query_vector.unwrap(), new_vector);
|
||||||
assert_eq!(query.limit.unwrap(), 100);
|
assert_eq!(query.limit.unwrap(), 100);
|
||||||
assert_eq!(query.nprobes, 1000);
|
assert_eq!(query.nprobes, 1000);
|
||||||
assert_eq!(query.use_index, true);
|
assert!(query.use_index);
|
||||||
assert_eq!(query.metric_type, Some(MetricType::Cosine));
|
assert_eq!(query.metric_type, Some(MetricType::Cosine));
|
||||||
assert_eq!(query.refine_factor, Some(999));
|
assert_eq!(query.refine_factor, Some(999));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -888,12 +888,12 @@ mod tests {
|
|||||||
|
|
||||||
let batches = make_test_batches();
|
let batches = make_test_batches();
|
||||||
let _ = batches.schema().clone();
|
let _ = batches.schema().clone();
|
||||||
NativeTable::create(&uri, "test", batches, None, None)
|
NativeTable::create(uri, "test", batches, None, None)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let batches = make_test_batches();
|
let batches = make_test_batches();
|
||||||
let result = NativeTable::create(&uri, "test", batches, None, None).await;
|
let result = NativeTable::create(uri, "test", batches, None, None).await;
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
result.unwrap_err(),
|
result.unwrap_err(),
|
||||||
Error::TableAlreadyExists { .. }
|
Error::TableAlreadyExists { .. }
|
||||||
@@ -906,7 +906,7 @@ mod tests {
|
|||||||
let uri = tmp_dir.path().to_str().unwrap();
|
let uri = tmp_dir.path().to_str().unwrap();
|
||||||
|
|
||||||
let batches = make_test_batches();
|
let batches = make_test_batches();
|
||||||
let table = NativeTable::create(&uri, "test", batches, None, None)
|
let table = NativeTable::create(uri, "test", batches, None, None)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@@ -924,7 +924,7 @@ mod tests {
|
|||||||
|
|
||||||
let batches = make_test_batches();
|
let batches = make_test_batches();
|
||||||
let schema = batches.schema().clone();
|
let schema = batches.schema().clone();
|
||||||
let table = NativeTable::create(&uri, "test", batches, None, None)
|
let table = NativeTable::create(uri, "test", batches, None, None)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(table.count_rows(None).await.unwrap(), 10);
|
assert_eq!(table.count_rows(None).await.unwrap(), 10);
|
||||||
@@ -952,7 +952,7 @@ mod tests {
|
|||||||
|
|
||||||
// Create a dataset with i=0..10
|
// Create a dataset with i=0..10
|
||||||
let batches = merge_insert_test_batches(0, 0);
|
let batches = merge_insert_test_batches(0, 0);
|
||||||
let table = NativeTable::create(&uri, "test", batches, None, None)
|
let table = NativeTable::create(uri, "test", batches, None, None)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(table.count_rows(None).await.unwrap(), 10);
|
assert_eq!(table.count_rows(None).await.unwrap(), 10);
|
||||||
@@ -1149,12 +1149,8 @@ mod tests {
|
|||||||
Arc::new(LargeStringArray::from_iter_values(vec![
|
Arc::new(LargeStringArray::from_iter_values(vec![
|
||||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
|
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
|
||||||
])),
|
])),
|
||||||
Arc::new(Float32Array::from_iter_values(
|
Arc::new(Float32Array::from_iter_values((0..10).map(|i| i as f32))),
|
||||||
(0..10).into_iter().map(|i| i as f32),
|
Arc::new(Float64Array::from_iter_values((0..10).map(|i| i as f64))),
|
||||||
)),
|
|
||||||
Arc::new(Float64Array::from_iter_values(
|
|
||||||
(0..10).into_iter().map(|i| i as f64),
|
|
||||||
)),
|
|
||||||
Arc::new(Into::<BooleanArray>::into(vec![
|
Arc::new(Into::<BooleanArray>::into(vec![
|
||||||
true, false, true, false, true, false, true, false, true, false,
|
true, false, true, false, true, false, true, false, true, false,
|
||||||
])),
|
])),
|
||||||
@@ -1163,14 +1159,14 @@ mod tests {
|
|||||||
Arc::new(TimestampMillisecondArray::from_iter_values(0..10)),
|
Arc::new(TimestampMillisecondArray::from_iter_values(0..10)),
|
||||||
Arc::new(
|
Arc::new(
|
||||||
create_fixed_size_list(
|
create_fixed_size_list(
|
||||||
Float32Array::from_iter_values((0..20).into_iter().map(|i| i as f32)),
|
Float32Array::from_iter_values((0..20).map(|i| i as f32)),
|
||||||
2,
|
2,
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
),
|
),
|
||||||
Arc::new(
|
Arc::new(
|
||||||
create_fixed_size_list(
|
create_fixed_size_list(
|
||||||
Float64Array::from_iter_values((0..20).into_iter().map(|i| i as f64)),
|
Float64Array::from_iter_values((0..20).map(|i| i as f64)),
|
||||||
2,
|
2,
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
@@ -1307,7 +1303,7 @@ mod tests {
|
|||||||
original: Arc<dyn object_store::ObjectStore>,
|
original: Arc<dyn object_store::ObjectStore>,
|
||||||
) -> Arc<dyn object_store::ObjectStore> {
|
) -> Arc<dyn object_store::ObjectStore> {
|
||||||
self.called.store(true, Ordering::Relaxed);
|
self.called.store(true, Ordering::Relaxed);
|
||||||
return original;
|
original
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1324,8 +1320,10 @@ mod tests {
|
|||||||
|
|
||||||
let wrapper = Arc::new(NoOpCacheWrapper::default());
|
let wrapper = Arc::new(NoOpCacheWrapper::default());
|
||||||
|
|
||||||
let mut object_store_params = ObjectStoreParams::default();
|
let object_store_params = ObjectStoreParams {
|
||||||
object_store_params.object_store_wrapper = Some(wrapper.clone());
|
object_store_wrapper: Some(wrapper.clone()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
let param = ReadParams {
|
let param = ReadParams {
|
||||||
store_options: Some(object_store_params),
|
store_options: Some(object_store_params),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
|||||||
Reference in New Issue
Block a user