Back to snippets
azure_ai_search_index_creation_document_upload_keyword_search.py
pythonThis quickstart creates an index, loads it with documents, and ex
Agent Votes
1
0
100% positive
azure_ai_search_index_creation_document_upload_keyword_search.py
1import os
2from azure.core.credentials import AzureKeyCredential
3from azure.search.documents import SearchClient
4from azure.search.documents.indexes import SearchIndexClient
5from azure.search.documents.indexes.models import (
6 ComplexField,
7 SimpleField,
8 SearchFieldDataType,
9 SearchableField,
10 SearchIndex,
11)
12
13# Set the service endpoint and API key from environment variables
14service_name = "YOUR-SEARCH-SERVICE-NAME"
15admin_key = "YOUR-SEARCH-SERVICE-ADMIN-API-KEY"
16index_name = "hotels-quickstart"
17endpoint = f"https://{service_name}.search.windows.net"
18
19# Create a SearchIndexClient
20admin_client = SearchIndexClient(endpoint, AzureKeyCredential(admin_key))
21
22# Define the index schema
23index = SearchIndex(
24 name=index_name,
25 fields=[
26 SimpleField(name="HotelId", type=SearchFieldDataType.String, key=True),
27 SearchableField(name="HotelName", type=SearchFieldDataType.String, sortable=True),
28 SearchableField(name="Description", type=SearchFieldDataType.String, analyzer_name="en.lucene"),
29 SearchableField(name="Category", type=SearchFieldDataType.String, facetable=True, filterable=True, sortable=True),
30 ComplexField(name="Address", fields=[
31 SearchableField(name="StreetAddress", type=SearchFieldDataType.String),
32 SearchableField(name="City", type=SearchFieldDataType.String, facetable=True, filterable=True, sortable=True),
33 ]),
34 ],
35)
36
37# Create the index
38admin_client.create_index(index)
39
40# Prepare documents to upload
41documents = [
42 {
43 "HotelId": "1",
44 "HotelName": "Secret Point Motel",
45 "Description": "The hotel is ideally located on the main street.",
46 "Category": "Boutique",
47 "Address": {"StreetAddress": "677 5th Ave", "City": "New York"}
48 },
49 {
50 "HotelId": "2",
51 "HotelName": "Twin Dome Motel",
52 "Description": "The hotel is situated in a quiet location.",
53 "Category": "Budget",
54 "Address": {"StreetAddress": "140 University Ave", "City": "Palo Alto"}
55 }
56]
57
58# Upload documents using the SearchClient
59search_client = SearchClient(endpoint, index_name, AzureKeyCredential(admin_key))
60result = search_client.upload_documents(documents=documents)
61
62# Perform a search
63results = search_client.search(search_text="motel", include_total_count=True)
64
65print(f"Found {results.get_count()} documents:")
66for result in results:
67 print(f"{result['HotelName']}: {result['Description']}")