> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Setting up Vectors for Fruits

> Demo demonstrating how to create, store, and query handcrafted 3D fruit vectors in a local LanceDB instance for similarity search using a mango query vector.

Hello and welcome back.

Now that we've covered similarity search concepts both theoretically and visually, let's implement the same example practically. We'll create a few handcrafted vectors for fruits and store them in a local LanceDB instance so we can run similarity comparisons. This demo uses simple 3-dimensional vectors representing hypothetical features (for example: sweetness, sourness, texture) so the results are easy to reason about.

Below are the steps to create the LanceDB table, insert the fruit vectors, and prepare a query vector for a mango.

<Callout icon="lightbulb" color="#1CB2FE">
  We use handcrafted 3-dimensional vectors here for clarity. In production, you would typically generate higher-dimensional embeddings using a machine learning model (for example, sentence or image encoders).
</Callout>

## 1) Setup: imports, paths, and model/table definition

Run the cell below to import dependencies, create a local directory for the DB, connect to [LanceDB](https://www.lancedb.org), and define a Pydantic-backed LanceModel schema for our fruit vectors.

```python theme={null}
import numpy as np
import lancedb
from lancedb.pydantic import LanceModel, Vector
from pathlib import Path

DB_PATH = Path("fruits_lancedb")
TABLE_NAME = "fruit_vectors"
DB_PATH.mkdir(exist_ok=True)

db = lancedb.connect(str(DB_PATH))

class FruitVector(LanceModel):
    name: str
    vector: Vector(3)

def prepare_table():
    if TABLE_NAME in db.table_names():
        db.drop_table(TABLE_NAME)
    return db.create_table(TABLE_NAME, schema=FruitVector)

table = prepare_table()
```

This creates (or recreates) a table named `fruit_vectors` in the local directory `fruits_lancedb`. If you point `lancedb.connect()` to a remote LanceDB instance, the DB files will be stored remotely and won't appear in the local directory.

## 2) Insert handcrafted fruit vectors

Define each fruit as a 3-dimensional NumPy vector and add the records to the LanceDB table. We convert vectors to plain Python lists (`vector.tolist()`) before insertion because LanceDB stores JSON-like serializable data.

```python theme={null}
fruit_vectors = {
    "papaya": np.array([0.88, 0.35, 0.05]),
    "peach": np.array([0.81, 0.32, 0.12]),
    "pear": np.array([0.62, 0.51, 0.38]),
    "pineapple": np.array([0.15, 0.85, 0.79]),
    "apple": np.array([0.28, 0.42, 0.69]),
    "apricot": np.array([0.77, 0.44, 0.21]),
    "guava": np.array([0.10, 0.74, 0.58]),
    "nectarine": np.array([0.83, 0.30, 0.11])
}

records = [
    {
        "name": name,
        "vector": vector.tolist(),
    }
    for name, vector in fruit_vectors.items()
]

table.add(records)

stored = table.to_pandas()
print(f"💾 Stored {len(stored)} handcrafted fruit vectors.")
print("Available fruits:", ", ".join(stored["name"].tolist()))
print(stored[["name", "vector"]])
```

Fruit vector summary (readable table):

| Fruit     | Vector (sweetness, sourness, texture) |
| --------- | ------------------------------------- |
| papaya    | `[0.88, 0.35, 0.05]`                  |
| peach     | `[0.81, 0.32, 0.12]`                  |
| pear      | `[0.62, 0.51, 0.38]`                  |
| pineapple | `[0.15, 0.85, 0.79]`                  |
| apple     | `[0.28, 0.42, 0.69]`                  |
| apricot   | `[0.77, 0.44, 0.21]`                  |
| guava     | `[0.10, 0.74, 0.58]`                  |
| nectarine | `[0.83, 0.30, 0.11]`                  |

<Callout icon="warning" color="#FF6B6B">
  A local directory named `fruits_lancedb` will be created and populated. If you run this demo multiple times, the table is dropped and recreated by `prepare_table()` to ensure a clean state.
</Callout>

Notes:

* Converting NumPy arrays via `vector.tolist()` ensures the data is JSON-serializable for LanceDB.
* Use `table.to_pandas()` to inspect stored records as a pandas DataFrame.

## 3) Prepare the query vector (mango)

Construct the mango query vector. This vector is used only for querying and is not inserted into the table in this demo (unless you intentionally add it).

```python theme={null}
mango_context = np.array([0.90, 0.34, 0.08])
print("✔ Query vector (mango):", mango_context.tolist())
```

Now you have:

* A LanceDB table `fruit_vectors` containing handcrafted 3-dimensional fruit vectors.
* A query vector `mango_context` ready for similarity comparisons.

## Next steps — similarity search examples

You can now run similarity searches (for example, cosine similarity, Euclidean distance, or dot product) against the stored vectors to see how the mango ranks among the fruits under different metrics. Typical steps:

* Normalize vectors (if using cosine similarity).
* Run a nearest-neighbors query in LanceDB using the mango vector.
* Compare top-k results across different metrics to see how rankings change.

Helpful links and references:

* [LanceDB Documentation](https://www.lancedb.org)
* [NumPy](https://numpy.org)
* [Pandas](https://pandas.pydata.org)
* [Pydantic](https://docs.pydantic.dev/)

What you might try next:

* Replace handcrafted vectors with model-generated embeddings (for example, text or image embeddings).
* Scale the table to higher-dimensional embeddings and larger datasets.
* Benchmark different similarity metrics (cosine vs. Euclidean vs. dot product) for your application.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/vector-database-for-genai/module/8e06787b-1ff8-4f2f-82f3-64f588e6637b/lesson/039fbc21-8dd5-4294-89b1-9805f90e7f75" />
</CardGroup>
