Azure SDK for JavaScript - Search
Welcome to the Azure SDK for JavaScript documentation for Azure Cognitive Search. This guide will help you integrate powerful search capabilities into your JavaScript applications.
Azure Cognitive Search is a cloud search service that provides developers with a scalable, RESTful API and SDKs for adding a rich search experience over application data to custom applications. It offers advanced features like full-text search, faceted navigation, suggestions, auto-completion, and geospatial search.
The Azure SDK for JavaScript provides a streamlined, idiomatic, and efficient way to interact with Azure services, including Azure Cognitive Search. We aim to provide a consistent and familiar development experience across all Azure SDKs.
Getting Started
Before you begin, ensure you have the following:
- An Azure Subscription.
- An Azure Cognitive Search service instance. You can create one from the Azure portal.
- Node.js installed on your development machine.
Install the Package
You can install the Azure Search SDK package using npm or yarn:
npm install @azure/search-documents
# or
yarn add @azure/search-documents
Authentication
To authenticate with your Azure Cognitive Search service, you can use either an API key or Azure Active Directory (AAD). For simplicity and quick starts, API keys are often used.
You can find your API key in the Azure portal under your Cognitive Search service's "Keys" section.
Basic Usage Example
Here's a simple example of how to connect to your service and perform a basic search:
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";
async function runSearch() {
const endpoint = "YOUR_SEARCH_SERVICE_ENDPOINT"; // e.g., "https://mysearchservice.search.windows.net"
const apiKey = "YOUR_SEARCH_API_KEY";
const indexName = "YOUR_INDEX_NAME"; // e.g., "hotels"
const credential = new AzureKeyCredential(apiKey);
const client = new SearchClient(endpoint, indexName, credential);
const searchResults = await client.search("*"); // Search for all documents
console.log("Search Results:");
for await (const hit of searchResults.results) {
console.log(` Score: ${hit.score}, Document:`, hit.document);
}
}
runSearch().catch((error) => {
console.error("The search operation failed:", error);
});
YOUR_SEARCH_SERVICE_ENDPOINT, YOUR_SEARCH_API_KEY, and YOUR_INDEX_NAME with your actual Azure Cognitive Search service details.
Core Concepts
- Search Service: The cloud-based service that hosts your search index.
- Search Index: A collection of documents that can be searched. Each document contains fields with searchable data.
- Documents: The individual items of data that you index and search.
- Fields: The properties within a document that define its searchable content and metadata.
- Query: The request made to the search index to retrieve documents.
- Search Options: Parameters that modify the behavior of a search query, such as filtering, faceting, ordering, and selecting fields.
Usage Examples
Indexing Documents
To index documents, you first need to define your index schema and then upload documents.
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";
async function uploadDocuments() {
const endpoint = "YOUR_SEARCH_SERVICE_ENDPOINT";
const apiKey = "YOUR_SEARCH_API_KEY";
const indexName = "YOUR_INDEX_NAME";
const credential = new AzureKeyCredential(apiKey);
const client = new SearchClient(endpoint, indexName, credential);
const documents = [
{
"id": "1",
"title": "Azure Functions Introduction",
"content": "Azure Functions is a serverless compute service that enables you to run code without provisioning or managing infrastructure."
},
{
"id": "2",
"title": "Getting Started with Azure Cosmos DB",
"content": "Azure Cosmos DB is a globally distributed, multi-model database service."
}
];
await client.uploadDocuments(documents);
console.log("Documents uploaded successfully.");
}
uploadDocuments().catch((error) => {
console.error("Document upload failed:", error);
});
Advanced Search Queries
Explore features like filtering, facets, and ordering.
import { SearchClient, AzureKeyCredential, SearchMode } from "@azure/search-documents";
async function advancedSearch() {
const endpoint = "YOUR_SEARCH_SERVICE_ENDPOINT";
const apiKey = "YOUR_SEARCH_API_KEY";
const indexName = "YOUR_INDEX_NAME";
const credential = new AzureKeyCredential(apiKey);
const client = new SearchClient(endpoint, indexName, credential);
const searchParameters = {
filter: "category eq 'electronics'",
facets: ["brand", "color"],
orderBy: ["price asc"],
searchMode: SearchMode.All, // e.g., "Azure AND Cosmos" requires both words
select: ["title", "price"]
};
const searchResults = await client.search("laptop", searchParameters);
console.log("Advanced Search Results:");
for (const facetResult of searchResults.facets) {
console.log(`Facet: ${facetResult.key}`);
for (const value of facetResult.values) {
console.log(` - ${value.value}: ${value.count}`);
}
}
for await (const hit of searchResults.results) {
console.log(` Document:`, hit.document);
}
}
advancedSearch().catch((error) => {
console.error("Advanced search failed:", error);
});
API Reference
The @azure/search-documents package provides clients for interacting with Azure Cognitive Search. Key classes and methods include:
| Class/Method | Description | Parameters |
|---|---|---|
SearchClient |
Client for performing search operations on a search index. | endpoint, indexName, credential |
SearchClient.search(...) |
Executes a search query against the index. | searchText, options? |
SearchClient.uploadDocuments(...) |
Uploads a batch of documents to the index. | documents, options? |
SearchClient.deleteDocuments(...) |
Deletes a batch of documents from the index. | documents, options? |
AzureKeyCredential |
Credential class for API key authentication. | key |
For a comprehensive API reference, please visit the official Azure SDK for JavaScript API documentation.
Best Practices
- Optimize Index Schema: Define your fields carefully, specifying their types, whether they are filterable, sortable, facetable, and searchable.
- Use Efficient Queries: Leverage filters and search modes to narrow down results. Consider using scoring profiles for relevance tuning.
- Handle Pagination: For large result sets, use the
skipandtopparameters to paginate through results. - Error Handling: Implement robust error handling for network issues, authentication failures, and search errors.
- Monitor Performance: Regularly monitor your search service performance in the Azure portal.