{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2db56c9b",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/LanceDBIndexDemo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "db0855d0",
   "metadata": {},
   "source": [
    "# LanceDB Vector Store\n",
    "In this notebook we are going to show how to use [LanceDB](https://www.lancedb.com) to perform vector searches in LlamaIndex"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f44170b2",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c84199c",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index llama-index-vector-stores-lancedb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a90ce34",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install lancedb==0.6.13 #Only required if the above cell installs an older version of lancedb (pypi package may not be released yet)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39c62671",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Refresh vector store URI if restarting or re-using the same notebook\n",
    "! rm -rf ./lancedb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59b54276",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import sys\n",
    "\n",
    "# Uncomment to see debug logs\n",
    "# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n",
    "# logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))\n",
    "\n",
    "\n",
    "from llama_index.core import SimpleDirectoryReader, Document, StorageContext\n",
    "from llama_index.core import VectorStoreIndex\n",
    "from llama_index.vector_stores.lancedb import LanceDBVectorStore\n",
    "import textwrap"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "26c71b6d",
   "metadata": {},
   "source": [
    "### Setup OpenAI\n",
    "The first step is to configure the openai key. It will be used to created embeddings for the documents loaded into the index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67b86621",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "openai.api_key = \"sk-\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "073f0a68",
   "metadata": {},
   "source": [
    "Download Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eef1b911",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2024-06-11 16:42:37--  https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 75042 (73K) [text/plain]\n",
      "Saving to: ‘data/paul_graham/paul_graham_essay.txt’\n",
      "\n",
      "data/paul_graham/pa 100%[===================>]  73.28K  --.-KB/s    in 0.02s   \n",
      "\n",
      "2024-06-11 16:42:37 (3.97 MB/s) - ‘data/paul_graham/paul_graham_essay.txt’ saved [75042/75042]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!mkdir -p 'data/paul_graham/'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f7010b1d-d1bb-4f08-9309-a328bb4ea396",
   "metadata": {},
   "source": [
    "### Loading documents\n",
    "Load the documents stored in the `data/paul_graham/` using the SimpleDirectoryReader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c154dd4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Document ID: cac1ba78-5007-4cf8-89ba-280264790115 Document Hash: fe2d4d3ef3a860780f6c2599808caa587c8be6516fe0ba4ca53cf117044ba953\n"
     ]
    }
   ],
   "source": [
    "documents = SimpleDirectoryReader(\"./data/paul_graham/\").load_data()\n",
    "print(\"Document ID:\", documents[0].doc_id, \"Document Hash:\", documents[0].hash)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c0232fd1",
   "metadata": {},
   "source": [
    "### Create the index\n",
    "Here we create an index backed by LanceDB using the documents loaded previously. LanceDBVectorStore takes a few arguments.\n",
    "- uri (str, required): Location where LanceDB will store its files.\n",
    "- table_name (str, optional): The table name where the embeddings will be stored. Defaults to \"vectors\".\n",
    "- nprobes (int, optional): The number of probes used. A higher number makes search more accurate but also slower. Defaults to 20.\n",
    "- refine_factor: (int, optional): Refine the results by reading extra elements and re-ranking them in memory. Defaults to None\n",
    "\n",
    "- More details can be found at [LanceDB docs](https://lancedb.github.io/lancedb/ann_indexes)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f2e20ef",
   "metadata": {},
   "source": [
    "##### For LanceDB cloud :\n",
    "```python\n",
    "vector_store = LanceDBVectorStore( \n",
    "    uri=\"db://db_name\", # your remote DB URI\n",
    "    api_key=\"sk_..\", # lancedb cloud api key\n",
    "    region=\"your-region\" # the region you configured\n",
    "    ...\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8731da62",
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_store = LanceDBVectorStore(\n",
    "    uri=\"./lancedb\", mode=\"overwrite\", query_type=\"hybrid\"\n",
    ")\n",
    "storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "\n",
    "index = VectorStoreIndex.from_documents(\n",
    "    documents, storage_context=storage_context\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8ee4473a-094f-4d0a-a825-e1213db07240",
   "metadata": {},
   "source": [
    "### Query the index\n",
    "We can now ask questions using our index. We can use filtering via `MetadataFilters` or use native lance `where` clause."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5eb6419b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.vector_stores import (\n",
    "    MetadataFilters,\n",
    "    FilterOperator,\n",
    "    FilterCondition,\n",
    "    MetadataFilter,\n",
    ")\n",
    "\n",
    "from datetime import datetime\n",
    "\n",
    "\n",
    "query_filters = MetadataFilters(\n",
    "    filters=[\n",
    "        MetadataFilter(\n",
    "            key=\"creation_date\",\n",
    "            operator=FilterOperator.EQ,\n",
    "            value=datetime.now().strftime(\"%Y-%m-%d\"),\n",
    "        ),\n",
    "        MetadataFilter(\n",
    "            key=\"file_size\", value=75040, operator=FilterOperator.GT\n",
    "        ),\n",
    "    ],\n",
    "    condition=FilterCondition.AND,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee201930",
   "metadata": {},
   "source": [
    "### Hybrid Search\n",
    "\n",
    "LanceDB offers hybrid search with reranking capabilities. For complete documentation, refer [here](https://lancedb.github.io/lancedb/hybrid_search/hybrid_search/).\n",
    "\n",
    "This example uses the `colbert` reranker. The following cell installs the necessary dependencies for `colbert`. If you choose a different reranker, make sure to adjust the dependencies accordingly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e12d1454",
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install -U torch transformers tantivy@git+https://github.com/quickwit-oss/tantivy-py#164adc87e1a033117001cf70e38c82a53014d985"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c742cb07",
   "metadata": {},
   "source": [
    "if you want to add a reranker at vector store initialization, you can pass it in the arguments like below :\n",
    "```\n",
    "from lancedb.rerankers import ColbertReranker\n",
    "reranker = ColbertReranker()\n",
    "vector_store = LanceDBVectorStore(uri=\"./lancedb\", reranker=reranker, mode=\"overwrite\")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27ea047b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import lancedb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8414517f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from lancedb.rerankers import ColbertReranker\n",
    "\n",
    "reranker = ColbertReranker()\n",
    "vector_store._add_reranker(reranker)\n",
    "\n",
    "query_engine = index.as_query_engine(\n",
    "    filters=query_filters,\n",
    "    # vector_store_kwargs={\n",
    "    #     \"query_type\": \"fts\",\n",
    "    # },\n",
    ")\n",
    "\n",
    "response = query_engine.query(\"How much did Viaweb charge per month?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc6ccb7a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Viaweb charged $100 a month for a small store and $300 a month for a big one.\n",
      "metadata - {'65ed5f07-5b8a-4143-a939-e8764884828e': {'file_path': '/Users/raghavdixit/Desktop/open_source/llama_index_lance/docs/docs/examples/vector_stores/data/paul_graham/paul_graham_essay.txt', 'file_name': 'paul_graham_essay.txt', 'file_type': 'text/plain', 'file_size': 75042, 'creation_date': '2024-06-11', 'last_modified_date': '2024-06-11'}, 'be231827-20b8-4988-ac75-94fa79b3c22e': {'file_path': '/Users/raghavdixit/Desktop/open_source/llama_index_lance/docs/docs/examples/vector_stores/data/paul_graham/paul_graham_essay.txt', 'file_name': 'paul_graham_essay.txt', 'file_type': 'text/plain', 'file_size': 75042, 'creation_date': '2024-06-11', 'last_modified_date': '2024-06-11'}}\n"
     ]
    }
   ],
   "source": [
    "print(response)\n",
    "print(\"metadata -\", response.metadata)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c1c6c73",
   "metadata": {},
   "source": [
    "##### lance filters(SQL like) directly via the `where` clause :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a2bcc07",
   "metadata": {},
   "outputs": [],
   "source": [
    "lance_filter = \"metadata.file_name = 'paul_graham_essay.txt' \"\n",
    "retriever = index.as_retriever(vector_store_kwargs={\"where\": lance_filter})\n",
    "response = retriever.retrieve(\"What did the author do growing up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ac47cf9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What I Worked On\n",
      "\n",
      "February 2021\n",
      "\n",
      "Before college the two main things I worked on, outside of school, were writing and programming. I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.\n",
      "\n",
      "The first programs I tried writing were on the IBM 1401 that our school district used for what was then called \"data processing.\" This was in 9th grade, so I was 13 or 14. The school district's 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain's lair down there, with all these alien-looking machines — CPU, disk drives, printer, card reader — sitting up on a raised floor under bright fluorescent lights.\n",
      "\n",
      "The language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.\n",
      "\n",
      "I was puzzled by the 1401. I couldn't figure out what to do with it. And in retrospect there's not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn't have any data stored on punched cards. The only other option was to do things that didn't rely on any input, like calculate approximations of pi, but I didn't know enough math to do anything interesting of that type. So I'm not surprised I can't remember any programs I wrote, because they can't have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn't. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager's expression made clear.\n",
      "\n",
      "With microcomputers, everything changed. Now you could have a computer sitting right in front of you, on a desk, that could respond to your keystrokes as it was running instead of just churning through a stack of punch cards and then stopping. [1]\n",
      "\n",
      "The first of my friends to get a microcomputer built it himself. It was sold as a kit by Heathkit. I remember vividly how impressed and envious I felt watching him sitting in front of it, typing programs right into the computer.\n",
      "\n",
      "Computers were expensive in those days and it took me years of nagging before I convinced my father to buy one, a TRS-80, in about 1980. The gold standard then was the Apple II, but a TRS-80 was good enough. This was when I really started programming. I wrote simple games, a program to predict how high my model rockets would fly, and a word processor that my father used to write at least one book. There was only room in memory for about 2 pages of text, so he'd write 2 pages at a time and then print them out, but it was a lot better than a typewriter.\n",
      "\n",
      "Though I liked programming, I didn't plan to study it in college. In college I was going to study philosophy, which sounded much more powerful. It seemed, to my naive high school self, to be the study of the ultimate truths, compared to which the things studied in other fields would be mere domain knowledge. What I discovered when I got to college was that the other fields took up so much of the space of ideas that there wasn't much left for these supposed ultimate truths. All that seemed left for philosophy were edge cases that people in other fields felt could safely be ignored.\n",
      "\n",
      "I couldn't have put this into words when I was 18. All I knew at the time was that I kept taking philosophy courses and they kept being boring. So I decided to switch to AI.\n",
      "\n",
      "AI was in the air in the mid 1980s, but there were two things especially that made me want to work on it: a novel by Heinlein called The Moon is a Harsh Mistress, which featured an intelligent computer called Mike, and a PBS documentary that showed Terry Winograd using SHRDLU. I haven't tried rereading The Moon is a Harsh Mistress, so I don't know how well it has aged, but when I read it I was drawn entirely into its world.\n",
      "metadata - {'file_path': '/Users/raghavdixit/Desktop/open_source/llama_index_lance/docs/docs/examples/vector_stores/data/paul_graham/paul_graham_essay.txt', 'file_name': 'paul_graham_essay.txt', 'file_type': 'text/plain', 'file_size': 75042, 'creation_date': '2024-06-11', 'last_modified_date': '2024-06-11'}\n"
     ]
    }
   ],
   "source": [
    "print(response[0].get_content())\n",
    "print(\"metadata -\", response[0].metadata)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6afc84ac",
   "metadata": {},
   "source": [
    "### Appending data\n",
    "You can also add data to an existing index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "759a532e",
   "metadata": {},
   "outputs": [],
   "source": [
    "nodes = [node.node for node in response]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "069fc099",
   "metadata": {},
   "outputs": [],
   "source": [
    "del index\n",
    "\n",
    "index = VectorStoreIndex.from_documents(\n",
    "    [Document(text=\"The sky is purple in Portland, Maine\")],\n",
    "    uri=\"/tmp/new_dataset\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a64ed441",
   "metadata": {},
   "outputs": [],
   "source": [
    "index.insert_nodes(nodes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5cffcfe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Portland, Maine\n"
     ]
    }
   ],
   "source": [
    "query_engine = index.as_query_engine()\n",
    "response = query_engine.query(\"Where is the sky purple?\")\n",
    "print(textwrap.fill(str(response), 100))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec548a02",
   "metadata": {},
   "source": [
    "You can also create an index from an existing table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc99404d",
   "metadata": {},
   "outputs": [],
   "source": [
    "del index\n",
    "\n",
    "vec_store = LanceDBVectorStore.from_table(vector_store._table)\n",
    "index = VectorStoreIndex.from_vector_store(vec_store)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b2e8cca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The author started Viaweb and Aspra.\n"
     ]
    }
   ],
   "source": [
    "query_engine = index.as_query_engine()\n",
    "response = query_engine.query(\"What companies did the author start?\")\n",
    "print(textwrap.fill(str(response), 100))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
