Azure Search Client
npm install azure-search-client
Usage
Basic query (async/await)
Use the async/await
pattern:
const SearchService = ; const client = 'myservice' 'mykey';const resp = await clientindexes;console; // array of result docs
Basic query (callback)
Or use the Node callback
pattern:
clientindexes;
Query API
Use the Azure Search POST query representation
If you are using TypeScript see how to use your own document models on index operations.
clientindexes;
Query builders
Use QueryBuilder
, QueryFilter
, QueryFacet
, and LambdaQueryFilter
helpers to build a query using method chaining.
Build a simple query:
await clientindexes top20 ;
Build a query with facets:
await clientindexes ;
There are multiple ways to specify facets (combine them as needed):
await clientindexes // simple facet parameters // callback builder // constructor builder // raw expression strings ;
Build an and
filtered query:
await clientindexes // by default, filters are chained with 'and' operator ;
Build an or
filtered query:
await clientindexes // chain filters with the 'or' operator ;
Build a not
filtered query:
await clientindexes // chain filters with the 'or' operator ;
Filter on geoDistance
:
await clientindexes // find documents less than 10km from the point at (122, 80) ;
Filter on a string collection:
await clientindexes // find documents where any member of 'myField1' is 'foo' ;
Build an arbitrarily complex filter graph:
await clientindexes ;
Specify filter as a raw string expression
await clientindexes ;
Escape user input when using Lucene query syntax.
await clientindexes // => "find at\&t documents" ;
All of the query builders support TypeScript Generics.
Indexing API
azure-search-client
automatically batches indexing operations up to 1000 documents or 16 MB, whichever is lower. Use either the fully buffered API (promise/callback based) or the streaming API, depending on your needs.
Fully buffered indexing API
Index documents using promise async
/await
const docs = ; // arbitrarily large array of document objectsconst results = await clientindexes indexdocs;
Or using a callback
const docs = ; // arbitrarily large array of document objectsclientindexes indexdocs { if err throw err; };
Streaming indexing API
When it is impractical to fully buffer an indexing payload, consider using the streaming API to pipe document objects into the index as fast as they can be read (while still buffering batches up to the Azure Search payload limits). This technique works best with streaming object sources like csv-parse
and json-stream
.
The Node pipeline API was introduced in Node.js 10.x. For use on older versions, consider using the .pipe() API.
const pipeline = ;const csvParse = ; // nmm i csv-parse
Request Options
You can set optional request-specific options for any request:
clientindexes;
You can set the default API version for your client:
const client = 'myService' 'myKey' 'myDefaultApiVersion';
JSON has no date representation, so Azure Search returns Date
fields as strings. The search client will automatically parse any string value that looks like a date, but you can disable date parsing in the request options:
clientindexes;
Any object with a list()
function accepts an optional $select
option to limit the fields that are fetched:
clientindexes;
Response properties
Every API response has some common properties (not every property is available for every request):
const resp = await clientindexes; // response bodyrespresult; // request idresppropertiesrequestId; // time spent by the search engineresppropertieselapsedTime // an identifier specified by the caller in the original request, if presentresppropertiesclientRequestId // An opaque string representing the current version of a resource (returned for indexers, indexes, and data sources, but not documents). Use this string in the If-Match or If-None-Match header for optimistic concurrency control.resppropertieseTag // The URL of the newly-created index definition for POST and PUT /indexes requests.resppropertieslocation // HTTP status code of the current requestrespstatusCode // Timestamp when the request startedresptimerstart // Node `hrtime` until the response headers arrivedresptimerresponse // Node `hrtime` until the full response body was readresptimerend
Manage search resources
With an admin key, the search client can manage the search resources
Manage Indexes
const indexes = clientindexes; // CREATE INDEXawait indexes; // LIST INDEXESawait indexes;
Manage an index
const index = clientindexes; // ANALYZE TEXTawait index; // COUNT DOCUMENTSawait index; // DELETE THE INDEXawait index; // GET THE SCHEMAawait index; // INDEX DOCUMENTS (add/update/delete)await indexindex /* IndexDocument */; // LOOKUP DOCUMENTawait index; // SEARCH DOCUMENTSawait index; // GET INDEX STATSawait index; // SUGGEST DOCUMENTSawait index;
Note:
search
,suggest
, andlookup
APIs will automatically parse document fields that look like Dates, returning JavaScriptDate
objects instead. To disable this, use the parseDate option
Manage Data Sources
const dataSources = clientdataSources; // dataSources => .create, .list
Manage a Data Source
const dataSource = clientdataSources; // dataSource => .get, .delete
Manage Indexers
const indexers = clientindexers; // indexers => .create, .list
Manage an Indexer
const indexer = clientindexers; // indexer => .get, .delete // RESET INDEXER STATEawait indexer; // RUN THE INDEXERawait indexer; // GET CURRENT INDEXER STATUSawait indexerstatus;
Manage Synonym Maps
const synonymMaps = clientsynonymMaps; // synonymMaps => .create, .list
Manage a Synonym Map
const synonymMap = clientsynonymMaps; // synonymMap => .get, .delete
Manage Skill Sets
SkillSets are currently in preview, so be sure to use
ApiVersion.preview
in theSearchService
constructor.When referencing a skill type, input name, or output name, be sure to use the corresponding
enum
value rather than a plain string value.
const skillSets = clientskillSets; // skillSets => .create, .list
Manage a Skill Set
const skillSet = clientskillSets; // skillSet => .get, .delete
TypeScript Generics
If you are using TypeScript, azure-search-client
has full support for your custom document types
Strongly typed documents are optional and default to
Document
, which allows for arbitrary document fields.
import { SearchService } from 'azure-search-client'; interface MyDoc { id: string; num: number;} const resp = await client.indexes.use<MyDoc>('myIndex').search({ search: 'hello',});const doc = resp.result.value[0];
doc
is typed as MyDoc & SearchDocument
, giving you compile-time access to id
and num
properties, as well as @search.score
and @search.highlights
.
Use your own Document types wherever documents are used: indexing, search, suggest.
When using a generic TDocument
parameter on your SearchIndex
, type safety also applies to the QueryBuilder
, QueryFilter
, and QueryFacet
utilities.
import { QueryFacet, QueryBuilder, QueryFilter } from 'azure-search-client'; interface MyDoc { id: string; num: number; date: Date; content: string;} const index = client.use<MyDoc>('myIndex'); const query = index.buildQuery() // or new QueryBuilder<MyDoc>() .searchFields('content') // ok .facet('num') // ok // compile errors since 'blah' and 'foo' are not part of the document model .buildFacet('blah', (facet) => facet.count(20)) .select('id', 'foo') .highlight('foo') .orderbyAsc('foo'); const filter = query.buildFilter((filter) => filter // or new QueryFilter<MyDoc>() .eq('id', 'foo') // ok .lt('date', new Date()) // ok .eq('num', 'oops, a string'); // compile failure: string is not assignable to number field