Skip to main content

Query data - Azure Cognitive Search

Query data in Node.js

To execute a simple search query in Node.js, create a new instance of the SearchIndexClient class provided by the Azure Cognitive Search SDK for Node.js. And create a new instance of the SearchParameters class to specify the search criteria.

Query data in Node.js
const { SearchIndexClient, AzureKeyCredential } = require('@azure/search-documents');

const endpoint = 'https://[SERVICE NAME].search.windows.net';
const apiKey = '[API KEY]';
const indexName = '[INDEX NAME]';

const client = new SearchIndexClient(endpoint, new AzureKeyCredential(apiKey));

const searchResult = await client.search('[SEARCH QUERY]', {
includeTotalCount: true,
});

console.log(`Total count of documents found: ${searchResult.count}`);
console.log(`Documents found:`);
console.log(searchResult.results);

Filters and Sorting

To refine search results based on specific criteria, such as date, category, or location, use filters and sorting in your search query.

Filters and sorting in a search query in Node.js
const { SearchIndexClient, AzureKeyCredential } = require('@azure/search-documents');

const endpoint = 'https://[SERVICE NAME].search.windows.net';
const apiKey = '[API KEY]';
const indexName = '[INDEX NAME]';

const client = new SearchIndexClient(endpoint, new AzureKeyCredential(apiKey));

const searchResult = await client.search('category:books', {
filter: 'price lt 50',
orderBy: ['price asc'],
});

console.log(`Total count of documents found: ${searchResult.count}`);
console.log(`Documents found:`);
console.log(searchResult.results);