opensearch-docs-cn/_clients/javascript/index.md

225 lines
6.6 KiB
Markdown
Raw Normal View History

2021-08-26 15:44:58 -04:00
---
layout: default
2021-09-30 16:52:34 -04:00
title: JavaScript client
has_children: true
nav_order: 40
2021-08-26 15:44:58 -04:00
---
# Getting started
2021-08-26 15:44:58 -04:00
The OpenSearch JavaScript (JS) client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster.
2021-08-26 15:44:58 -04:00
The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. The example here demonstrates some basic operations like creating an index, adding documents, and searching your data.
## Setup
2021-09-30 16:52:34 -04:00
To add the client to your project, install it from [npm](https://www.npmjs.com):
2021-08-26 15:44:58 -04:00
```bash
2021-09-22 15:26:41 -04:00
npm install @opensearch-project/opensearch
2021-08-26 15:44:58 -04:00
```
To install a specific major version of the client, run the following command:
```bash
2021-09-22 15:26:41 -04:00
npm install @opensearch-project/opensearch@<version>
```
2021-08-26 15:44:58 -04:00
If you prefer to add the client manually or just want to examine the source code, see [opensearch-js](https://github.com/opensearch-project/opensearch-js) on GitHub.
Then require the client:
```javascript
2021-09-22 15:26:41 -04:00
const { Client } = require("@opensearch-project/opensearch");
2021-08-26 15:44:58 -04:00
```
## Sample code
```javascript
2021-09-22 15:26:41 -04:00
"use strict";
2021-08-26 15:44:58 -04:00
2021-09-22 15:26:41 -04:00
var host = "localhost";
var protocol = "https";
2021-08-26 15:44:58 -04:00
var port = 9200;
2021-09-22 15:26:41 -04:00
var auth = "admin:admin"; // For testing only. Don't store credentials in code.
var ca_certs_path = "/full/path/to/root-ca.pem";
2021-08-26 15:44:58 -04:00
// Optional client certificates if you don't want to use HTTP basic authentication.
// var client_cert_path = '/full/path/to/client.pem'
// var client_key_path = '/full/path/to/client-key.pem'
// Create a client with SSL/TLS enabled.
2021-09-22 15:27:39 -04:00
var { Client } = require("@opensearch-project/opensearch");
2021-09-22 15:26:41 -04:00
var fs = require("fs");
2021-08-26 15:44:58 -04:00
var client = new Client({
2021-09-22 15:26:41 -04:00
node: protocol + "://" + auth + "@" + host + ":" + port,
ssl: {
ca: fs.readFileSync(ca_certs_path),
// You can turn off certificate verification (rejectUnauthorized: false) if you're using self-signed certificates with a hostname mismatch.
// cert: fs.readFileSync(client_cert_path),
// key: fs.readFileSync(client_key_path)
},
});
2021-08-26 15:44:58 -04:00
async function search() {
2021-09-22 15:26:41 -04:00
// Create an index with non-default settings.
var index_name = "books";
var settings = {
settings: {
index: {
number_of_shards: 4,
number_of_replicas: 3,
},
},
};
var response = await client.indices.create({
index: index_name,
body: settings,
});
console.log("Creating index:");
console.log(response.body);
// Add a document to the index.
var document = {
title: "The Outsider",
author: "Stephen King",
year: "2018",
genre: "Crime fiction",
};
var id = "1";
var response = await client.index({
id: id,
index: index_name,
body: document,
refresh: true,
});
console.log("Adding document:");
console.log(response.body);
// Search for the document.
var query = {
query: {
match: {
title: {
query: "The Outsider",
},
},
},
};
var response = await client.search({
index: index_name,
body: query,
});
console.log("Search results:");
console.log(response.body.hits);
// Delete the document.
var response = await client.delete({
index: index_name,
id: id,
});
console.log("Deleting document:");
console.log(response.body);
// Delete the index.
var response = await client.indices.delete({
index: index_name,
});
console.log("Deleting index:");
console.log(response.body);
2021-08-26 15:44:58 -04:00
}
2021-09-22 15:26:41 -04:00
search().catch(console.log);
2021-08-26 15:44:58 -04:00
```
## Authenticate with Amazon OpenSearch Service - AWS Sigv4
Use the following code to authenticate with AWS V2 SDK:
```javascript
const AWS = require('aws-sdk'); // V2 SDK.
const { Client } = require('@opensearch-project/opensearch');
const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
const client = new Client({
...AwsSigv4Signer({
region: 'us-east-1',
// Must return a Promise that resolve to an AWS.Credentials object.
// This function is used to acquire the credentials when the client start and
// when the credentials are expired.
// The Client will refresh the Credentials only when they are expired.
// With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
// Example with AWS SDK V2:
getCredentials: () =>
new Promise((resolve, reject) => {
// Any other method to acquire a new Credentials object can be used.
AWS.config.getCredentials((err, credentials) => {
if (err) {
reject(err);
} else {
resolve(credentials);
}
});
}),
}),
node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
});
```
Use the following code to authenticate with AWS V3 SDK:
```javascript
const { defaultProvider } = require("@aws-sdk/credential-provider-node"); // V3 SDK.
const { Client } = require('@opensearch-project/opensearch');
const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
const client = new Client({
...AwsSigv4Signer({
region: 'us-east-1',
// Must return a Promise that resolve to an AWS.Credentials object.
// This function is used to acquire the credentials when the client start and
// when the credentials are expired.
// The Client will refresh the Credentials only when they are expired.
// With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
// Example with AWS SDK V3:
getCredentials: () => {
// Any other method to acquire a new Credentials object can be used.
const credentialsProvider = defaultProvider();
return credentialsProvider();
},
}),
node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
});
```
## Circuit breaker
The `memoryCircuitBreaker` option can be used to prevent errors caused by a response payload being too large to fit into the heap memory available to the client.
The `memoryCircuitBreaker` object contains two fields:
- `enabled`: A Boolean used to turn the circuit breaker on or off. Defaults to `false`.
- `maxPercentage`: The threshold that determines whether the circuit breaker engages. Valid values are floats in the [0, 1] range that represent percentages in decimal form. Any value that exceeds that range will correct to `1.0`.
The following example instantiates a client with the circuit breaker enabled and its threshold set to 80% of the available heap size limit:
```javascript
var client = new Client({
memoryCircuitBreaker: {
enabled: true,
maxPercentage: 0.8,
},
});
```