Skip to content

Commit 83809cb

Browse files
authored
Merge pull request #2 from lobrien/lobrien_quickstart
Azure Search Node.js quickstart
2 parents 031ef04 + 3ecae94 commit 83809cb

12 files changed

+590
-17
lines changed

.gitignore

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,58 +4,43 @@ logs
44
npm-debug.log*
55
yarn-debug.log*
66
yarn-error.log*
7-
87
# Runtime data
98
pids
109
*.pid
1110
*.seed
1211
*.pid.lock
13-
1412
# Directory for instrumented libs generated by jscoverage/JSCover
1513
lib-cov
16-
1714
# Coverage directory used by tools like istanbul
1815
coverage
19-
2016
# nyc test coverage
2117
.nyc_output
22-
2318
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
2419
.grunt
25-
2620
# Bower dependency directory (https://bower.io/)
2721
bower_components
28-
2922
# node-waf configuration
3023
.lock-wscript
31-
3224
# Compiled binary addons (https://nodejs.org/api/addons.html)
3325
build/Release
34-
3526
# Dependency directories
3627
node_modules/
3728
jspm_packages/
38-
3929
# TypeScript v1 declaration files
4030
typings/
41-
4231
# Optional npm cache directory
4332
.npm
44-
4533
# Optional eslint cache
4634
.eslintcache
47-
4835
# Optional REPL history
4936
.node_repl_history
50-
5137
# Output of 'npm pack'
5238
*.tgz
53-
5439
# Yarn Integrity file
5540
.yarn-integrity
56-
5741
# dotenv environment variables file
5842
.env
59-
6043
# next.js build output
6144
.next
45+
**/.vscode/*
46+
package-lock.json

quickstart/.eslintrc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"extends": ["airbnb-base", "prettier"]
3+
}

quickstart/.prettierrc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"singleQuote": true,
3+
"tabWidth" : 4
4+
}

quickstart/AzureSearchClient.js

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
const fetch = require('node-fetch');
2+
3+
class AzureSearchClient {
4+
constructor(searchServiceName, adminKey, queryKey, indexName) {
5+
this.searchServiceName = searchServiceName;
6+
this.adminKey = adminKey;
7+
// The query key is used for read-only requests and so can be distributed with less risk of abuse.
8+
this.queryKey = queryKey;
9+
this.indexName = indexName;
10+
this.apiVersion = '2019-05-06';
11+
}
12+
13+
getIndexUrl() { return `https://${this.searchServiceName}.search.windows.net/indexes/${this.indexName}?api-version=${this.apiVersion}`; }
14+
15+
getPostDataUrl() { return `https://${this.searchServiceName}.search.windows.net/indexes/${this.indexName}/docs/index?api-version=${this.apiVersion}`; }
16+
17+
getSearchUrl(searchTerm) { return `https://${this.searchServiceName}.search.windows.net/indexes/${this.indexName}/docs?api-version=${this.apiVersion}&search=${searchTerm}&searchMode=all`; }
18+
19+
static async request(url, method, apiKey, bodyJson = null) {
20+
// Uncomment the following for request details:
21+
/*
22+
console.log(`\n${method} ${url}`);
23+
console.log(`\nKey ${apiKey}`);
24+
if (bodyJson !== null) {
25+
console.log(`\ncontent: ${JSON.stringify(bodyJson, null, 4)}`);
26+
}
27+
*/
28+
29+
const headers = {
30+
'content-type' : 'application/json',
31+
'api-key' : apiKey
32+
};
33+
const init = bodyJson === null ?
34+
{
35+
method,
36+
headers
37+
}
38+
:
39+
{
40+
method,
41+
headers,
42+
body : JSON.stringify(bodyJson)
43+
};
44+
return fetch(url, init);
45+
}
46+
47+
static throwOnHttpError(response) {
48+
const statusCode = response.status;
49+
if (statusCode >= 300){
50+
console.log(`Request failed: ${JSON.stringify(response, null, 4)}`);
51+
throw new Error(`Failure in request. HTTP Status was ${statusCode}`);
52+
}
53+
}
54+
55+
async indexExistsAsync() {
56+
console.log("\n Checking if index exists...");
57+
const endpoint = this.getIndexUrl();
58+
const response = await AzureSearchClient.request(endpoint, "GET", this.adminKey);
59+
// Success has a few likely status codes: 200 or 204 (No Content), but accept all in 200 range...
60+
const exists = response.status >= 200 && response.status < 300;
61+
return exists;
62+
}
63+
64+
async deleteIndexAsync() {
65+
console.log("\n Deleting existing index...");
66+
const endpoint = this.getIndexUrl();
67+
const response = await AzureSearchClient.request(endpoint, "DELETE", this.adminKey);
68+
AzureSearchClient.throwOnHttpError(response);
69+
return this;
70+
}
71+
72+
async createIndexAsync(definition) {
73+
console.log("\n Creating index...");
74+
const endpoint = this.getIndexUrl();
75+
const response = await AzureSearchClient.request(endpoint, "PUT", this.adminKey, definition);
76+
AzureSearchClient.throwOnHttpError(response);
77+
return this;
78+
}
79+
80+
async postDataAsync(hotelsData) {
81+
console.log("\n Adding hotel data...");
82+
const endpoint = this.getPostDataUrl();
83+
const response = await AzureSearchClient.request(endpoint,"POST", this.adminKey, hotelsData);
84+
AzureSearchClient.throwOnHttpError(response);
85+
return this;
86+
}
87+
88+
async queryAsync(searchTerm) {
89+
console.log("\n Querying...")
90+
const endpoint = this.getSearchUrl(searchTerm);
91+
const response = await AzureSearchClient.request(endpoint, "GET", this.queryKey);
92+
AzureSearchClient.throwOnHttpError(response);
93+
return response;
94+
}
95+
}
96+
97+
module.exports = AzureSearchClient;

quickstart/CONTRIBUTING.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Contributing to Azure Search Quickstart
2+
3+
This project welcomes contributions and suggestions. Most contributions require you to agree to a
4+
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
5+
the rights to use your contribution. For details, visit https://cla.microsoft.com.
6+
7+
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
8+
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
9+
provided by the bot. You will only need to do this once across all repos using our CLA.
10+
11+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
12+
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
13+
contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
14+
15+
- [Code of Conduct](#coc)
16+
- [Issues and Bugs](#issue)
17+
- [Feature Requests](#feature)
18+
- [Submission Guidelines](#submit)
19+
20+
## <a name="coc"></a> Code of Conduct
21+
Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
22+
23+
## <a name="issue"></a> Found an Issue?
24+
If you find a bug in the source code or a mistake in the documentation, you can help us by
25+
[submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
26+
[submit a Pull Request](#submit-pr) with a fix.
27+
28+
## <a name="feature"></a> Want a Feature?
29+
You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
30+
Repository. If you would like to *implement* a new feature, please submit an issue with
31+
a proposal for your work first, to be sure that we can use it.
32+
33+
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
34+
35+
## <a name="submit"></a> Submission Guidelines
36+
37+
### <a name="submit-issue"></a> Submitting an Issue
38+
Before you submit an issue, search the archive, maybe your question was already answered.
39+
40+
If your issue appears to be a bug, and hasn't been reported, open a new issue.
41+
Help us to maximize the effort we can spend fixing issues and adding new
42+
features, by not reporting duplicate issues. Providing the following information will increase the
43+
chances of your issue being dealt with quickly:
44+
45+
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
46+
* **Version** - what version is affected (e.g. 0.1.2)
47+
* **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
48+
* **Browsers and Operating System** - is this a problem with all browsers?
49+
* **Reproduce the Error** - provide a live example or a unambiguous set of steps
50+
* **Related Issues** - has a similar issue been reported before?
51+
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
52+
causing the problem (line of code or commit)
53+
54+
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new].
55+
56+
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
57+
Before you submit your Pull Request (PR) consider the following guidelines:
58+
59+
* Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR
60+
that relates to your submission. You don't want to duplicate effort.
61+
62+
* Make your changes in a new git fork:
63+
64+
* Commit your changes using a descriptive commit message
65+
* Push your fork to GitHub:
66+
* In GitHub, create a pull request
67+
* If we suggest changes then:
68+
* Make the required updates.
69+
* Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
70+
71+
```shell
72+
git rebase master -i
73+
git push -f
74+
```
75+
76+
That's it! Thank you for your contribution!

quickstart/LICENSE.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) Microsoft Corporation. All rights reserved.
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE

quickstart/README.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
---
2+
page-type: sample
3+
languages:
4+
- nodejs
5+
name: Quickstart in Node.js
6+
description: |
7+
Learn basic steps for creating, loading, and querying an Azure Search index using REST APIs and Node.js.
8+
products:
9+
- azure
10+
- azure-search
11+
urlFragment: nodejs-quickstart
12+
---
13+
14+
# Quickstart sample for Azure Search with Node.js
15+
16+
![Quickstart sample MIT license badge](https://img.shields.io/badge/license-MIT-green.svg)
17+
18+
Demonstrates using Node.js and the Azure Search REST API to create an index, load it with documents, and execute a few queries. The index is modeled on a subset of the Hotels dataset, reduced for readability and comprehension. Index definition and documents are included in the code.
19+
20+
This Node.js console application is featured in [Node.js Quickstart: Create, load, and query indexes using Azure Search REST APIs](https://docs.microsoft.com/azure/search/search-get-started-nodejs). When you run the program, a console window emits output messages for each step: deleting and then re-creating a hotels-quickstart index, loading documents, running queries. This sample uses the [REST API](https://docs.microsoft.com/en-us/rest/api/searchservice/) and runs on an Azure Search service using connection information that you provide.
21+
22+
## Contents
23+
24+
| File/folder | Description |
25+
|-------------|-------------|
26+
| `index.js` | The main program |
27+
| `AzureSearchClient.js` | Defines a class that can makes Azure Search REST API requests. |
28+
| `azure_search_config.json` | Key-value configuration data. |
29+
| `hotels_quickstart_index.json` | Specifies the structure of the Azure Search index. |
30+
| `hotels.json` | A small amount of sample data to populate Azure Search. |
31+
| `package.json` | The Node project definition file. |
32+
| `package-lock.json` | The version dependencies of the project. |
33+
| `.eslintrc` | Coding standards used by [ESLint](https://eslint.org/). |
34+
| `.prettierrc` | Formatting standards used by [Prettier](https://prettier.io/). |
35+
| `.gitignore` | Define what to ignore at commit time. |
36+
| `CONTRIBUTING.md` | Guidelines for contributing to the sample. |
37+
| `README.md` | This README file. |
38+
| `LICENSE.md` | The license for the sample. |
39+
40+
## Prerequisites
41+
42+
+ [Node.js](https://nodejs.org).
43+
+ [NPM](https://www.npmjs.com) should be installed by Node.js.
44+
+ [Create an Azure Search service](search-create-service-portal.md) or [find an existing service](https://ms.portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.Search%2FsearchServices) under your current subscription. You can use a free service for this quickstart.
45+
46+
Recommended:
47+
48+
* [Visual Studio Code](https://code.visualstudio.com).
49+
* [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) and [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) extensions for VSCode.
50+
51+
## Setup
52+
53+
1. Clone or download this sample repository.
54+
1. Run the following command to install the node dependencies.
55+
```bash
56+
npm install
57+
```
58+
1. Modify the values in `azure_search_config.json`
59+
1. Replace `[SEARCH_SERVICE_NAME]` with the name of your search service.
60+
1. Replace `[SEARCH_SERVICE_ADMIN_KEY]` with either of the admin keys of your search service.
61+
1. Replace `[SEARCH_SERVICE_QUERY_KEY]` with the query key of your search service
62+
63+
### Running quickstart
64+
65+
1. Run the following command to start the program.
66+
```bash
67+
node index.js
68+
```
69+
70+
You should see a series of messages relating to the creation of the search index, adding documents to it, and, finally, results of a series of queries.
71+
72+
## Key concepts
73+
74+
The file **hotels_quickstart_index.json** holds the definition of an index for the data in the file **hotels.json**. Review those files to see the fields, which ones are searchable, etc.
75+
76+
The file **AzureSearchClient.js** defines a class, `AzureSearchClient` that knows how to construct the URLs of the REST API and prepare and execute an HTTP request using the `fetch` API. It uses the query API key for queries and, otherwise, uses the admin API key.
77+
78+
The file **index.js** reads the **azure_search_config.json** file, and passes the configuration data it finds there to the constructor of `AzureSearchClient`. The `sleep` function is used to pause execution in between major steps such as creating the index, submitting data for indexing, etc. Such pauses are generally only needed in test, demo, and sample code.
79+
80+
The `run` function :
81+
82+
* Checks if the `hotels-quickstart` index exists.
83+
* If so, the program deletes the existing index.
84+
* Creates a new `hotels-quickstart` index from the structure in **hotels_quickstart_index.json**.
85+
* Adds the data from **hotels.json** to the `hotels-quickstart` index.
86+
* Executes a few basic queries against the search index.
87+
88+
## Next steps
89+
90+
You can learn more about Azure Search on the [official documentation site](https://docs.microsoft.com/azure/search/).
91+

quickstart/azure_search_config.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"serviceName" : "[SEARCH_SERVICE_NAME]",
3+
"adminKey" : "[SEARCH_SERVICE_ADMIN_KEY]",
4+
"queryKey" : "[SEARCH_SERVICE_QUERY_KEY]",
5+
"indexName" : "hotels-quickstart"
6+
}

0 commit comments

Comments
 (0)