-
Notifications
You must be signed in to change notification settings - Fork 532
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
AI Search - Full text search (wip) (#74)
* AI Search - Full text search (wip) * AI Search - full-text search * remove unused type * cleanup * fix search terms * edit * Cleanup * edit
- Loading branch information
Showing
6 changed files
with
525 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
SEARCH_API_KEY=<YOUR-SEARCH-ADMIN-API-KEY> | ||
SEARCH_API_ENDPOINT=<YOUR-SEARCH-SERVICE-URL> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"name": "ai-search-full-text-search-quickstart", | ||
"version": "1.0.0", | ||
"type": "module", | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1", | ||
"build": "tsc", | ||
"prettier:fix": "prettier --write \"src/**/*.ts\"" | ||
}, | ||
"author": "", | ||
"license": "ISC", | ||
"description": "", | ||
"dependencies": { | ||
"@azure/identity": "^4.3.0", | ||
"@azure/search-documents": "^12.1.0", | ||
"dotenv": "^16.4.5" | ||
}, | ||
"devDependencies": { | ||
"@types/node": "^20.12.2", | ||
"@typescript-eslint/parser": "^5.62.0", | ||
"eslint": "^8.57.0", | ||
"prettier": "^3.3.3", | ||
"prettier-eslint": "^16.3.0", | ||
"ts-node": "^10.9.2", | ||
"typescript": "^5.4.3" | ||
}, | ||
"prettier": { | ||
"printWidth": 80 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,275 @@ | ||
import { | ||
SearchIndexClient, | ||
SimpleField, | ||
ComplexField, | ||
SearchSuggester, | ||
SearchClient, | ||
SearchDocumentsResult, | ||
AzureKeyCredential, | ||
odata, | ||
SearchFieldArray, | ||
SearchIndex, | ||
} from "@azure/search-documents"; | ||
import "dotenv/config"; | ||
|
||
// Import data | ||
import indexDefinition from "./hotels_quickstart_index.json" with { type: "json" }; | ||
import hotelData from "./hotels.json" with { type: "json" }; | ||
|
||
// Get endpoint and apiKey from .env file | ||
const endpoint: string = process.env.SEARCH_API_ENDPOINT!!; | ||
const apiKey: string = process.env.SEARCH_API_KEY!!; | ||
if (!endpoint || !apiKey) { | ||
throw new Error( | ||
"Make sure to set valid values for endpoint and apiKey with proper authorization.", | ||
); | ||
} | ||
|
||
function printSearchIndex(searchIndex: SearchIndex) { | ||
const { name, etag, defaultScoringProfile } = searchIndex; | ||
console.log( | ||
`Search Index name: ${name}, etag: ${etag}, defaultScoringProfile: ${defaultScoringProfile}`, | ||
); | ||
} | ||
function wait(ms: number): Promise<void> { | ||
return new Promise((resolve) => setTimeout(resolve, ms)); | ||
} | ||
|
||
type MyIndexDefinition = { | ||
name: string; | ||
fields: SimpleField[] | ComplexField[]; | ||
suggesters: SearchSuggester[]; | ||
}; | ||
type Hotel = { | ||
HotelId: string; | ||
HotelName: string; | ||
Description: string; | ||
Description_fr: string; | ||
Category: string; | ||
Tags: string[]; | ||
ParkingIncluded: string | boolean; | ||
LastRenovationDate: string; | ||
Rating: number; | ||
Address: Address; | ||
}; | ||
type Address = { | ||
StreetAddress: string; | ||
City: string; | ||
StateProvince: string; | ||
PostalCode: string; | ||
}; | ||
|
||
// Get Incoming Data | ||
const indexDef: SearchIndex = indexDefinition as MyIndexDefinition; | ||
const hotels: Hotel[] = hotelData["value"]; | ||
|
||
async function createIndex( | ||
searchIndexClient: SearchIndexClient, | ||
indexName: string, | ||
searchIndex: SearchIndex, | ||
) { | ||
console.log(`Running Azure AI Search JavaScript quickstart...`); | ||
|
||
// Delete the index if it already exists | ||
indexName | ||
? await searchIndexClient.deleteIndex(indexName) | ||
: console.log("Index doesn't exist."); | ||
|
||
console.log("Creating index..."); | ||
const newIndex: SearchIndex = await searchIndexClient.createIndex(searchIndex); | ||
|
||
// Print the new index | ||
printSearchIndex(newIndex); | ||
} | ||
async function loadData( | ||
searchClient: any, | ||
hotels: any, | ||
) { | ||
console.log("Uploading documents..."); | ||
|
||
let indexDocumentsResult = await searchClient.mergeOrUploadDocuments(hotels); | ||
|
||
console.log(JSON.stringify(indexDocumentsResult)); | ||
|
||
console.log( | ||
`Index operations succeeded: ${JSON.stringify(indexDocumentsResult.results[0].succeeded)}`, | ||
); | ||
} | ||
|
||
async function searchAllReturnAllFields( | ||
searchClient: SearchClient<Hotel>, | ||
searchText: string, | ||
) { | ||
console.log("Query #1 - return everything:"); | ||
|
||
// Search Options | ||
// Without `select` property, all fields are returned | ||
const searchOptions = { includeTotalCount: true }; | ||
|
||
// Search | ||
const { count, results } = await searchClient.search( | ||
searchText, | ||
searchOptions, | ||
); | ||
|
||
// Show results | ||
for await (const result of results) { | ||
console.log(`${JSON.stringify(result.document)}`); | ||
} | ||
|
||
// Show results count | ||
console.log(`Result count: ${count}`); | ||
} | ||
async function searchAllSelectReturnedFields( | ||
searchClient: SearchClient<Hotel>, | ||
searchText: string, | ||
) { | ||
console.log("Query #2 - search everything:"); | ||
|
||
// Search Options | ||
// Narrow down the fields to return | ||
const selectFields: SearchFieldArray<Hotel> = [ | ||
"HotelId", | ||
"HotelName", | ||
"Rating", | ||
]; | ||
const searchOptions = { includeTotalCount: true, select: selectFields }; | ||
|
||
// Search | ||
const { count, results }: SearchDocumentsResult<Hotel> = | ||
await searchClient.search(searchText, searchOptions); | ||
|
||
// Show results | ||
for await (const result of results) { | ||
console.log(`${JSON.stringify(result.document)}`); | ||
} | ||
|
||
// Show results count | ||
console.log(`Result count: ${count}`); | ||
} | ||
async function searchWithFilterOrderByAndSelect( | ||
searchClient: SearchClient<Hotel>, | ||
searchText: string, | ||
filterText: string, | ||
) { | ||
console.log("Query #3 - Search with filter, orderBy, and select:"); | ||
|
||
// Search Options | ||
// Narrow down the fields to return | ||
const searchOptions = { | ||
filter: odata`Address/StateProvince eq ${filterText}`, | ||
orderBy: ["Rating desc"], | ||
select: ["HotelId", "HotelName", "Rating"] as const, // Select only these fields | ||
}; | ||
type SelectedHotelFields = Pick<Hotel, "HotelId" | "HotelName" | "Rating">; | ||
|
||
// Search | ||
const { count, results }: SearchDocumentsResult<SelectedHotelFields> = | ||
await searchClient.search(searchText, searchOptions); | ||
|
||
// Show results | ||
for await (const result of results) { | ||
console.log(`${JSON.stringify(result.document)}`); | ||
} | ||
|
||
// Show results count | ||
console.log(`Result count: ${count}`); | ||
} | ||
async function searchWithLimitedSearchFields( | ||
searchClient: SearchClient<Hotel>, | ||
searchText: string, | ||
) { | ||
console.log("Query #4 - Limit searchFields:"); | ||
|
||
// Search Options | ||
const searchOptions = { | ||
select: ["HotelId", "HotelName", "Rating"] as const, // Select only these fields | ||
searchFields: ["HotelName"] as const, | ||
}; | ||
type SelectedHotelFields = Pick<Hotel, "HotelId" | "HotelName" | "Rating">; | ||
|
||
// Search | ||
const { count, results }: SearchDocumentsResult<SelectedHotelFields> = | ||
await searchClient.search(searchText, searchOptions); | ||
|
||
// Show results | ||
for await (const result of results) { | ||
console.log(`${JSON.stringify(result.document)}`); | ||
} | ||
|
||
// Show results count | ||
console.log(`Result count: ${count}`); | ||
} | ||
async function searchWithFacets( | ||
searchClient: SearchClient<Hotel>, | ||
searchText: string, | ||
) { | ||
console.log("Query #5 - Use facets:"); | ||
|
||
// Search Options | ||
const searchOptions = { | ||
facets: ["Category"], //For aggregation queries | ||
select: ["HotelId", "HotelName", "Rating"] as const, // Select only these fields | ||
searchFields: ["HotelName"] as const, | ||
}; | ||
type SelectedHotelFields = Pick<Hotel, "HotelName">; | ||
|
||
// Search | ||
const { count, results }: SearchDocumentsResult<SelectedHotelFields> = | ||
await searchClient.search(searchText, searchOptions); | ||
|
||
// Show results | ||
for await (const result of results) { | ||
console.log(`${JSON.stringify(result.document)}`); | ||
} | ||
|
||
// Show results count | ||
console.log(`Result count: ${count}`); | ||
} | ||
async function lookupDocumentById( | ||
searchClient: SearchClient<Hotel>, | ||
key: string, | ||
) { | ||
console.log("Query #6 - Lookup document:"); | ||
|
||
// Get document by ID | ||
// Full document returned, destructured into id and name | ||
const { HotelId: id, HotelName: name }: Hotel = | ||
await searchClient.getDocument(key); | ||
|
||
// Show results | ||
console.log(`HotelId: ${id}, HotelName: ${name}`); | ||
} | ||
|
||
async function main(indexName: string, indexDef: SearchIndex, hotels: Hotel[]) { | ||
// Create a new SearchIndexClient | ||
const indexClient = new SearchIndexClient( | ||
endpoint, | ||
new AzureKeyCredential(apiKey), | ||
); | ||
|
||
// Create the index | ||
await createIndex(indexClient, indexName, indexDef); | ||
|
||
const searchClient = indexClient.getSearchClient(indexName); | ||
//const searchClient = new SearchClient(endpoint, indexName, new AzureKeyCredential(apiKey)); | ||
|
||
|
||
// Load with data | ||
console.log("Loading data...", indexName); | ||
await loadData(searchClient, hotels); | ||
|
||
wait(10000); | ||
|
||
// Search index | ||
// await searchAllReturnAllFields(searchClient, "*"); | ||
// await searchAllSelectReturnedFields(searchClient, "*"); | ||
// await searchWithFilterOrderByAndSelect(searchClient, "wifi", "FL"); | ||
// await searchWithLimitedSearchFields(searchClient, "sublime cliff"); | ||
// await searchWithFacets(searchClient, "*"); | ||
// await lookupDocumentById(searchClient, "3"); | ||
} | ||
|
||
main(indexDefinition?.name, indexDef, hotels).catch((err) => { | ||
console.error("The sample encountered an error:", err); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
{ | ||
"value": [ | ||
{ | ||
"HotelId": "1", | ||
"HotelName": "Secret Point Motel", | ||
"Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", | ||
"Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", | ||
"Category": "Boutique", | ||
"Tags": ["pool", "air conditioning", "concierge"], | ||
"ParkingIncluded": false, | ||
"LastRenovationDate": "1970-01-18T00:00:00Z", | ||
"Rating": 3.6, | ||
"Address": { | ||
"StreetAddress": "677 5th Ave", | ||
"City": "New York", | ||
"StateProvince": "NY", | ||
"PostalCode": "10022" | ||
} | ||
}, | ||
{ | ||
"HotelId": "2", | ||
"HotelName": "Twin Dome Motel", | ||
"Description": "The hotel is situated in a nineteenth century plaza, which has been expanded and renovated to the highest architectural standards to create a modern, functional and first-class hotel in which art and unique historical elements coexist with the most modern comforts.", | ||
"Description_fr": "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.", | ||
"Category": "Boutique", | ||
"Tags": ["pool", "free wifi", "concierge"], | ||
"ParkingIncluded": "false", | ||
"LastRenovationDate": "1979-02-18T00:00:00Z", | ||
"Rating": 3.6, | ||
"Address": { | ||
"StreetAddress": "140 University Town Center Dr", | ||
"City": "Sarasota", | ||
"StateProvince": "FL", | ||
"PostalCode": "34243" | ||
} | ||
}, | ||
{ | ||
"HotelId": "3", | ||
"HotelName": "Triple Landscape Hotel", | ||
"Description": "The Hotel stands out for its gastronomic excellence under the management of William Dough, who advises on and oversees all of the Hotel’s restaurant services.", | ||
"Description_fr": "L'hôtel est situé dans une place du XIXe siècle, qui a été agrandie et rénovée aux plus hautes normes architecturales pour créer un hôtel moderne, fonctionnel et de première classe dans lequel l'art et les éléments historiques uniques coexistent avec le confort le plus moderne.", | ||
"Category": "Resort and Spa", | ||
"Tags": ["air conditioning", "bar", "continental breakfast"], | ||
"ParkingIncluded": "true", | ||
"LastRenovationDate": "2015-09-20T00:00:00Z", | ||
"Rating": 4.8, | ||
"Address": { | ||
"StreetAddress": "3393 Peachtree Rd", | ||
"City": "Atlanta", | ||
"StateProvince": "GA", | ||
"PostalCode": "30326" | ||
} | ||
}, | ||
{ | ||
"HotelId": "4", | ||
"HotelName": "Sublime Cliff Hotel", | ||
"Description": "Sublime Cliff Hotel is located in the heart of the historic center of Sublime in an extremely vibrant and lively area within short walking distance to the sites and landmarks of the city and is surrounded by the extraordinary beauty of churches, buildings, shops and monuments. Sublime Cliff is part of a lovingly restored 1800 palace.", | ||
"Description_fr": "Le sublime Cliff Hotel est situé au coeur du centre historique de sublime dans un quartier extrêmement animé et vivant, à courte distance de marche des sites et monuments de la ville et est entouré par l'extraordinaire beauté des églises, des bâtiments, des commerces et Monuments. Sublime Cliff fait partie d'un Palace 1800 restauré avec amour.", | ||
"Category": "Boutique", | ||
"Tags": ["concierge", "view", "24-hour front desk service"], | ||
"ParkingIncluded": true, | ||
"LastRenovationDate": "1960-02-06T00:00:00Z", | ||
"Rating": 4.6, | ||
"Address": { | ||
"StreetAddress": "7400 San Pedro Ave", | ||
"City": "San Antonio", | ||
"StateProvince": "TX", | ||
"PostalCode": "78216" | ||
} | ||
} | ||
] | ||
} |
Oops, something went wrong.