@ -6,14 +6,14 @@
"source": [
"# Azure Cognitive Search\n",
"\n",
"> [Azure Cognitive Search](https://learn.microsoft.com/en-us /azure/search/search-what-is-azure-search) (formerly known as `Azure Search`) is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n"
"[Azure Cognitive Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) (formerly known as `Azure Search`) is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Install Azure Cognitive Search SDK"
"# Install Azure Cognitive Search SDK"
]
},
{
@ -22,11 +22,12 @@
"metadata": {},
"outputs": [],
"source": [
"!pip install --index-url=https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-python/pypi/simple/ azure-search-documents==11.4.0a20230509004 \n",
"!pip install azure-search-documents==11.4.0b6 \n",
"!pip install azure-identity"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@ -39,14 +40,14 @@
"metadata": {},
"outputs": [],
"source": [
"import os, json\n",
"import openai\n",
"from dotenv import load_dotenv \n",
"import os \n",
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
"from langchain.vectorstores.azuresearch import AzureSearch"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@ -60,13 +61,10 @@
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables from a .env file using load_dotenv():\n",
"load_dotenv()\n",
"\n",
"openai.api_type = \"azure\"\n",
"openai.api_base = \"YOUR_OPENAI_ENDPOINT\"\n",
"openai.api_version = \"2023-05-15\"\n",
"openai.api_key = \"YOUR_OPENAI_API_KEY\"\n",
"os.environ[\"OPENAI_API_TYPE\"] = \"azure\"\n",
"os.environ[\"OPENAI_API_BASE\"] = \"YOUR_OPENAI_ENDPOINT\"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_API_KEY\"\n",
"os.environ[\"OPENAI_API_VERSION\"] = \"2023-05-15\"\n",
"model: str = \"text-embedding-ada-002\""
]
},
@ -81,13 +79,12 @@
},
{
"cell_type": "code",
"execution_count": 10 ,
"execution_count": 9 ,
"metadata": {},
"outputs": [],
"source": [
"vector_store_address: str = \"YOUR_AZURE_SEARCH_ENDPOINT\"\n",
"vector_store_password: str = \"YOUR_AZURE_SEARCH_ADMIN_KEY\"\n",
"index_name: str = \"langchain-vector-demo\""
"vector_store_password: str = \"YOUR_AZURE_SEARCH_ADMIN_KEY\""
]
},
{
@ -101,11 +98,12 @@
},
{
"cell_type": "code",
"execution_count": 11 ,
"execution_count": 10 ,
"metadata": {},
"outputs": [],
"source": [
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(model=model, chunk_size=1)\n",
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"index_name: str = \"langchain-vector-demo\"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
@ -125,7 +123,7 @@
},
{
"cell_type": "code",
"execution_count": 12 ,
"execution_count": null ,
"metadata": {},
"outputs": [],
"source": [
@ -142,6 +140,7 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
@ -152,7 +151,7 @@
},
{
"cell_type": "code",
"execution_count": 13 ,
"execution_count": 15 ,
"metadata": {},
"outputs": [
{
@ -180,17 +179,18 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Perform a Hybrid Search\n",
"\n",
"Execute hybrid search using the hybrid_search() method:"
"Execute hybrid search using the search_type or hybrid_search() method:"
]
},
{
"cell_type": "code",
"execution_count": 14 ,
"execution_count": null ,
"metadata": {},
"outputs": [
{
@ -210,15 +210,358 @@
"source": [
"# Perform a hybrid search\n",
"docs = vector_store.similarity_search(\n",
" query=\"What did the president say about Ketanji Brown Jackson\", k=3\n",
" query=\"What did the president say about Ketanji Brown Jackson\",\n",
" k=3, \n",
" search_type=\"hybrid\"\n",
")\n",
"print(docs[0].page_content)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’ re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
"\n",
"Tonight, I’ d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
"\n",
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
"\n",
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’ s top legal minds, who will continue Justice Breyer’ s legacy of excellence.\n"
]
}
],
"source": [
"# Perform a hybrid search\n",
"docs = vector_store.hybrid_search(\n",
" query=\"What did the president say about Ketanji Brown Jackson\", \n",
" k=3\n",
")\n",
"print(docs[0].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create a new index with custom filterable fields "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"from azure.search.documents.indexes.models import (\n",
" SearchableField,\n",
" SearchField,\n",
" SearchFieldDataType,\n",
" SimpleField,\n",
" ScoringProfile,\n",
" TextWeights,\n",
")\n",
"\n",
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"embedding_function = embeddings.embed_query\n",
"\n",
"fields = [\n",
" SimpleField(\n",
" name=\"id\",\n",
" type=SearchFieldDataType.String,\n",
" key=True,\n",
" filterable=True,\n",
" ),\n",
" SearchableField(\n",
" name=\"content\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" SearchField(\n",
" name=\"content_vector\",\n",
" type=SearchFieldDataType.Collection(SearchFieldDataType.Single),\n",
" searchable=True,\n",
" vector_search_dimensions=len(embedding_function(\"Text\")),\n",
" vector_search_configuration=\"default\",\n",
" ),\n",
" SearchableField(\n",
" name=\"metadata\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field to store the title\n",
" SearchableField(\n",
" name=\"title\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field for filtering on document source\n",
" SimpleField(\n",
" name=\"source\",\n",
" type=SearchFieldDataType.String,\n",
" filterable=True,\n",
" ),\n",
"]\n",
"\n",
"index_name: str = \"langchain-vector-demo-custom\"\n",
"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
" index_name=index_name,\n",
" embedding_function=embedding_function,\n",
" fields=fields,\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Perform a query with a custom filter"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"# Data in the metadata dictionary with a corresponding field in the index will be added to the index\n",
"# In this example, the metadata dictionary contains a title, a source and a random field\n",
"# The title and the source will be added to the index as separate fields, but the random won't. (as it is not defined in the fields list)\n",
"# The random field will be only stored in the metadata field\n",
"vector_store.add_texts(\n",
" [\"Test 1\", \"Test 2\", \"Test 3\"],\n",
" [\n",
" {\"title\": \"Title 1\", \"source\": \"A\", \"random\": \"10290\"},\n",
" {\"title\": \"Title 2\", \"source\": \"A\", \"random\": \"48392\"},\n",
" {\"title\": \"Title 3\", \"source\": \"B\", \"random\": \"32893\"},\n",
" ],\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 3', metadata={'title': 'Title 3', 'source': 'B', 'random': '32893'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'A', 'random': '10290'}),\n",
" Document(page_content='Test 2', metadata={'title': 'Title 2', 'source': 'A', 'random': '48392'})]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 3 source1\", k=3, search_type=\"hybrid\")\n",
"res"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'A', 'random': '10290'}),\n",
" Document(page_content='Test 2', metadata={'title': 'Title 2', 'source': 'A', 'random': '48392'})]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 3 source1\", k=3, search_type=\"hybrid\", filters=\"source eq 'A'\")\n",
"res"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create a new index with a Scoring Profile"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"from azure.search.documents.indexes.models import (\n",
" SearchableField,\n",
" SearchField,\n",
" SearchFieldDataType,\n",
" SimpleField,\n",
" ScoringProfile,\n",
" TextWeights,\n",
" ScoringFunction,\n",
" FreshnessScoringFunction,\n",
" FreshnessScoringParameters\n",
")\n",
"\n",
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"embedding_function = embeddings.embed_query\n",
"\n",
"fields = [\n",
" SimpleField(\n",
" name=\"id\",\n",
" type=SearchFieldDataType.String,\n",
" key=True,\n",
" filterable=True,\n",
" ),\n",
" SearchableField(\n",
" name=\"content\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" SearchField(\n",
" name=\"content_vector\",\n",
" type=SearchFieldDataType.Collection(SearchFieldDataType.Single),\n",
" searchable=True,\n",
" vector_search_dimensions=len(embedding_function(\"Text\")),\n",
" vector_search_configuration=\"default\",\n",
" ),\n",
" SearchableField(\n",
" name=\"metadata\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field to store the title\n",
" SearchableField(\n",
" name=\"title\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field for filtering on document source\n",
" SimpleField(\n",
" name=\"source\",\n",
" type=SearchFieldDataType.String,\n",
" filterable=True,\n",
" ),\n",
" # Additional data field for last doc update\n",
" SimpleField(\n",
" name=\"last_update\",\n",
" type=SearchFieldDataType.DateTimeOffset,\n",
" searchable=True,\n",
" filterable=True\n",
" )\n",
"]\n",
"# Adding a custom scoring profile with a freshness function\n",
"sc_name = \"scoring_profile\"\n",
"sc = ScoringProfile(\n",
" name=sc_name,\n",
" text_weights=TextWeights(weights={\"title\": 5}),\n",
" function_aggregation=\"sum\",\n",
" functions=[\n",
" FreshnessScoringFunction(\n",
" field_name=\"last_update\",\n",
" boost=100,\n",
" parameters=FreshnessScoringParameters(boosting_duration=\"P2D\"),\n",
" interpolation=\"linear\"\n",
" )\n",
" ]\n",
")\n",
"\n",
"index_name = \"langchain-vector-demo-custom-scoring-profile\"\n",
"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
" index_name=index_name,\n",
" embedding_function=embeddings.embed_query,\n",
" fields=fields,\n",
" scoring_profiles = [sc],\n",
" default_scoring_profile = sc_name\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['NjQyNTI5ZmMtNmVkYS00Njg5LTk2ZDgtMjM3OTY4NTJkYzFj',\n",
" 'M2M0MGExZjAtMjhiZC00ZDkwLThmMTgtODNlN2Y2ZDVkMTMw',\n",
" 'ZmFhMDE1NzMtMjZjNS00MTFiLTk0MTEtNGRkYjgwYWQwOTI0']"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Adding same data with different last_update to show Scoring Profile effect\n",
"from datetime import datetime, timedelta\n",
"\n",
"today = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"yesterday = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"one_month_ago = (datetime.utcnow() - timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"\n",
"vector_store.add_texts(\n",
" [\"Test 1\", \"Test 1\", \"Test 1\"],\n",
" [\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"10290\", \"last_update\": today},\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"48392\", \"last_update\": yesterday},\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"32893\", \"last_update\": one_month_ago},\n",
" ],\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '10290', 'last_update': '2023-07-13T10:47:39-00:00'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '48392', 'last_update': '2023-07-12T10:47:39-00:00'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '32893', 'last_update': '2023-06-13T10:47:39-00:00'})]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 1\", k=3, search_type=\"hybrid\")\n",
"res"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3.9.13 ('.venv': venv )",
"language": "python",
"name": "python3"
},
@ -232,8 +575,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.6 "
"version": "3.9.13 "
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "645053d6307d413a1a75681b5ebb6449bb2babba4bcb0bf65a1ddc3dbefb108a"
@ -241,5 +585,5 @@
}
},
"nbformat": 4,
"nbformat_minor": 4
"nbformat_minor": 2
}