@opensearch-project/opensearch 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,28 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
9
9
  ### Deprecated
10
10
  ### Removed
11
11
  ### Fixed
12
+
13
+ ## [2.6.0]
14
+ ### Added
15
+ - Inherit AwsSigV4 in .child ([#725](https://github.com/opensearch-project/opensearch-js/pull/725))
16
+ ### Dependencies
17
+ - Bumps `prettier` from 3.1.1 to 3.2.5
18
+ - Bumps `@aws-sdk/types` from 3.485.0 to 3.523.0
19
+ - Bumps `@types/node` from 20.10.7 to 20.11.24
20
+ - Bumps `eslint-plugin-prettier` from 5.1.2 to 5.1.3
21
+ - Bumps `@babel/eslint-parser` from 7.23.3 to 7.23.10
22
+ - Bumps `semver` from 7.5.1 to 7.6.0
23
+ - Bumps `cross-zip` from 4.0.0 to 4.0.1
24
+ - Bumps `eslint` from 8.56.0 to 8.57.0
25
+ ### Changed
26
+ - Updated integration tests to use strong password in OS 2.12 and up ([#707](https://github.com/opensearch-project/opensearch-js/pull/707))
27
+ - Simplified client creation in the guides ([#707](https://github.com/opensearch-project/opensearch-js/pull/707))
28
+ - Corrected `guides/bulk.md` ([#616](https://github.com/opensearch-project/opensearch-js/issues/616))
29
+ ### Deprecated
30
+ ### Removed
31
+ - Removed AutoHeal([#707](https://github.com/opensearch-project/opensearch-js/pull/707))
32
+ ### Fixed
33
+ - Make optional fields optional in `MappingGenericProperty` ([708](https://github.com/opensearch-project/opensearch-js/pull/708))
12
34
  ### Security
13
35
 
14
36
  ## [2.5.0]
@@ -69,6 +91,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
69
91
  ### Deprecated
70
92
  ### Removed
71
93
  ### Fixed
94
+ - Fix wrong documentation for file serach.md regarding `search_after` param ([#584](https://github.com/opensearch-project/opensearch-js/pull/584))
72
95
  ### Security
73
96
 
74
97
  ## [2.3.0]
@@ -220,4 +243,4 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
220
243
 
221
244
  ### Fixed
222
245
 
223
- - Fix mutability of connection headers ([#291](https://github.com/opensearch-project/opensearch-js/issues/291))
246
+ - Fix mutability of connection headers ([#291](https://github.com/opensearch-project/opensearch-js/issues/291))
package/USER_GUIDE.md CHANGED
@@ -26,7 +26,7 @@
26
26
  var host = 'localhost';
27
27
  var protocol = 'https';
28
28
  var port = 9200;
29
- var auth = 'admin:admin'; // For testing only. Don't store credentials in code.
29
+ var auth = 'admin:strongPassword@999'; // For testing only. Don't store credentials in code.
30
30
  var ca_certs_path = '/full/path/to/root-ca.pem';
31
31
 
32
32
  // Optional client certificates if you don't want to use HTTP basic authentication.
package/api/types.d.ts CHANGED
@@ -3907,17 +3907,17 @@ export interface MappingFloatRangeProperty extends MappingRangePropertyBase {
3907
3907
  }
3908
3908
 
3909
3909
  export interface MappingGenericProperty extends MappingDocValuesPropertyBase {
3910
- analyzer: string;
3911
- boost: double;
3912
- fielddata: IndicesStringFielddata;
3913
- ignore_malformed: boolean;
3914
- index: boolean;
3915
- index_options: MappingIndexOptions;
3916
- norms: boolean;
3917
- null_value: string;
3918
- position_increment_gap: integer;
3919
- search_analyzer: string;
3920
- term_vector: MappingTermVectorOption;
3910
+ analyzer?: string;
3911
+ boost?: double;
3912
+ fielddata?: IndicesStringFielddata;
3913
+ ignore_malformed?: boolean;
3914
+ index?: boolean;
3915
+ index_options?: MappingIndexOptions;
3916
+ norms?: boolean;
3917
+ null_value?: string;
3918
+ position_increment_gap?: integer;
3919
+ search_analyzer?: string;
3920
+ term_vector?: MappingTermVectorOption;
3921
3921
  type: string;
3922
3922
  }
3923
3923
 
@@ -6,10 +6,11 @@ In this guide, we will look at some advanced index actions that are not covered
6
6
  Let's create a client instance, and an index named `movies`:
7
7
  ```javascript
8
8
  const { Client } = require('@opensearch-project/opensearch');
9
+
9
10
  const client = new Client({
10
- node: 'https://admin:admin@localhost:9200',
11
- ssl: { rejectUnauthorized: false }
11
+ node: 'http://localhost:9200',
12
12
  });
13
+
13
14
  client.indices.create({index: 'movies'})
14
15
  ```
15
16
  ## API Actions
package/guides/bulk.md CHANGED
@@ -19,143 +19,103 @@ Next, create an index named `movies` and another named `books` with the default
19
19
  const movies = 'movies';
20
20
  const books = 'books';
21
21
 
22
- client.indices.create({ index: movies }).then(() => {
23
- console.log(`Index ${movies} created`);
24
- });
22
+ if ((await client.indices.exists({ index: movies })).body)
23
+ await client.indices.delete({ index: movies });
24
+ if ((await client.indices.exists({ index: books })).body)
25
+ await client.indices.delete({ index: books });
25
26
 
26
- client.indices.create({ index: books }).then(() => {
27
- console.log(`Index ${books} created`);
28
- });
27
+ await client.indices.create({ index: movies });
28
+ await client.indices.create({ index: books });
29
29
  ```
30
30
 
31
31
 
32
32
  ## Bulk API
33
33
 
34
- The `bulk` API action allows you to perform document operations in a single request. The body of the request is an array of objects that contains the bulk operations and the target documents to index, create, update, or delete.
34
+ The `bulk` API action allows you to perform multiple document operations in a single request. The body of the request is an array of objects that contains the bulk operations and the target documents to index, create, update, or delete.
35
35
 
36
36
  ### Indexing multiple documents
37
- The following code creates two documents in the `movies` index and one document in the `books` index:
38
-
39
- ```javascript
40
- client.bulk({
41
- body: [
42
- { index: { _index: movies, _id: 1 } },
43
- { title: 'Beauty and the Beast', year: 1991 },
44
- { index: { _index: movies, _id: 2 } },
45
- { title: 'Beauty and the Beast - Live Action', year: 2017 },
46
- { index: { _index: books, _id: 1 } },
47
- { title: 'The Lion King', year: 1994 }
48
- ]
49
- }).then((response) => {
50
- console.log(response);
51
- });
52
- ```
53
- As you can see, each bulk operation is comprised of two objects. The first object contains the operation type and the target document's `_index` and `_id`. The second object contains the document's data. As a result, the body of the request above contains six objects for three index actions.
54
-
55
- Alternatively, the `bulk` method can accept an array of hashes where each hash represents a single operation. The following code is equivalent to the previous example:
56
-
57
- ```javascript
58
- client.bulk({
59
- body: [
60
- { index: { _index: movies, _id: 1, data: { title: 'Beauty and the Beast', year: 1991 } } },
61
- { index: { _index: movies, _id: 2, data: { title: 'Beauty and the Beast - Live Action', year: 2017 } } },
62
- { index: { _index: books, _id: 1, data: { title: 'The Lion King', year: 1994 } } }
63
- ]
64
- }).then((response) => {
65
- console.log(response);
66
- });
67
- ```
68
-
69
- We will use this format for the rest of the examples in this guide.
70
37
 
71
- ### Creating multiple documents
38
+ The following code create 3 documents in the `movies` index and one in the `books` index using the `bulk` API action:
72
39
 
73
- Similarly, instead of calling the `create` method for each document, you can use the `bulk` API to create multiple documents in a single request. The following code creates three documents in the `movies` index and one in the `books` index:
74
40
 
75
41
  ```javascript
76
- client.bulk({
77
- index: movies,
78
- body: [
79
- { create: { data: { title: 'Beauty and the Beast 2', year: 2030 } } },
80
- { create: { data: { title: 'Beauty and the Beast 3', year: 2031 } } },
81
- { create: { data: { title: 'Beauty and the Beast 4', year: 2049 } } },
82
- { create: { _index: books, data: { title: 'The Lion King 2', year: 1998 } } }
83
- ]
84
- }).then((response) => {
85
- console.log(response);
86
- });
42
+ client
43
+ .bulk({
44
+ index: movies, // the default index
45
+ body: [
46
+ { create: {} },
47
+ { title: 'Beauty and the Beast', year: 2030, director: 'Ella' },
48
+ { index : {} },
49
+ { title: 'Snow White', year: 2031, director: 'Jake' },
50
+ { create: {} },
51
+ { title: 'Cinderella', year: 2032, director: 'Clyde' },
52
+ { index: { _index: books } },
53
+ { title: 'The Lion King', year: 1994, author: 'John' },
54
+ ],
55
+ })
56
+ .then((response) => {
57
+ console.log(response.body.items);
58
+ });
87
59
  ```
88
- Note that we specified only the `_index` for the last document in the request body. This is because the `bulk` method accepts an `index` parameter that specifies the default `_index` for all bulk operations in the request body. Moreover, we omit the `_id` for each document and let OpenSearch generate them for us in this example, just like we can with the `create` method.
60
+ As you can see, each `create` operation comprises 2 objects: the first object contain the directive for the operation, and the second object is the document to be indexed. Notice that the first 3 operations do not specify the index name, so the `movies` index is used by default.
89
61
 
90
- ### Updating multiple documents
91
- ```javascript
92
- client.bulk({
93
- index: movies,
94
- body: [
95
- { update: { _id: 1, data: { doc: { year: 1992 } } } },
96
- { update: { _id: 2, data: { doc: { year: 2018 } } } }
97
- ]
98
- }).then((response) => {
99
- console.log(response);
100
- });
101
- ```
102
- Note that the updated data is specified in the `doc` field of the `data` object.
62
+ ### Mixing Operations
103
63
 
64
+ Take a look at the code block below:
104
65
 
105
- ### Deleting multiple documents
106
66
  ```javascript
107
- client.bulk({
108
- index: movies,
109
- body: [
110
- { delete: { _id: 1 } },
111
- { delete: { _id: 2 } }
112
- ]
113
- }).then((response) => {
114
- console.log(response);
115
- });
67
+ client
68
+ .bulk({
69
+ index: movies, // The default index
70
+ body: [
71
+ { create: { _id: 1 } },
72
+ { title: 'Beauty and the Beast 1', year: 2050 },
73
+
74
+ { delete: { _id: 1 } },
75
+
76
+ { create: { _id: 2 } },
77
+ { title: 'Beauty and the Beast 2', year: 2051 },
78
+
79
+ { create: {} },
80
+ { title: 'Beauty and the Beast 2', year: 2051 },
81
+
82
+ { create: { _index: books } },
83
+ { title: '2012', year: 2012 },
84
+ ],
85
+ })
86
+ .then((response) => {
87
+ console.log(response.body.items);
88
+ });
116
89
  ```
117
90
 
118
- ### Mix and match operations
119
- You can mix and match the different operations in a single request. The following code creates two documents, updates one document, and deletes another document:
91
+ This single `bulk` request contains 5 operations:
92
+ - Creates a document with the ID `1` in the `movies` index.
93
+ - Deletes the document with the ID `1` in the `movies` index.
94
+ - Creates a document with the ID `2` in the `movies` index.
95
+ - Creates a document in the `movies` index (since `_id` is not specified, a new ID is generated automatically).
96
+ - Creates a document in the `books` index (since `movies` is the default index, you have to specify `books` for `_index`).
120
97
 
121
- ```javascript
122
- client.bulk({
123
- index: movies,
124
- body: [
125
- { create: { data: { title: 'Beauty and the Beast 5', year: 2050 } } },
126
- { create: { data: { title: 'Beauty and the Beast 6', year: 2051 } } },
127
- { update: { _id: 3, data: { doc: { year: 2052 } } } },
128
- { delete: { _id: 4 } }
129
- ]
130
- }).then((response) => {
131
- console.log(response);
132
- });
133
- ```
134
98
 
135
- ### Handling errors
136
- The `bulk` API returns an array of responses for each operation in the request body. Each response contains a `status` field that indicates whether the operation was successful or not. If the operation was successful, the `status` field is set to a `2xx` code. Otherwise, the response contains an error message in the `error` field.
99
+ ## Bulk Helper
137
100
 
138
- The following code shows how to look for errors in the response:
101
+ The OpenSearch JavaScript client provides a `bulk` helper that simplifies the process of creating a bulk request for operations of the same type. The following code block demonstrates how to use the `bulk` helper to create one document in the `movies` index for each item in the `docs` array:
139
102
 
140
103
  ```javascript
141
- client.bulk({
142
- index: movies,
143
- body: [
144
- { create: { _id: 1, data: { title: 'Beauty and the Beast', year: 1991 } } },
145
- { create: { _id: 2, data: { title: 'Beauty and the Beast 2', year: 2030 } } },
146
- { create: { _id: 1, data: { title: 'Beauty and the Beast 3', year: 2031 } } }, // document already exists error
147
- { create: { _id: 2, data: { title: 'Beauty and the Beast 4', year: 2049 } } } // document already exists error
148
- ]
149
- }).then((response) => {
150
- response.body.forEach((item) => {
151
- const createStatus = item.create && item.create.status;
152
- if (createStatus && !createStatus.toString().match(/2\d{2}/)) {
153
- console.log(item.create.error.reason);
154
- }
104
+ const docs = [
105
+ { title: 'Beauty and the Beast 1', year: 2050 },
106
+ { title: 'Beauty and the Beast 2', year: 2051 },
107
+ ];
108
+
109
+ client.helpers
110
+ .bulk({
111
+ datasource: docs,
112
+ onDocument(_) {
113
+ return { index: { _index: movies } };
114
+ },
115
+ })
116
+ .then((result) => {
117
+ console.log(result);
155
118
  });
156
- }).catch((error) => {
157
- console.error(error);
158
- });
159
119
  ```
160
120
 
161
121
  ## Cleanup
@@ -163,4 +123,4 @@ To clean up the resources created in this guide, delete the `movies` and `books`
163
123
 
164
124
  ```javascript
165
125
  client.indices.delete({ index: [movies, books] });
166
- ```
126
+ ```
@@ -3,23 +3,13 @@ This guide covers OpenSearch JavaScript Client API actions for Index Lifecycle.
3
3
 
4
4
  ## Setup
5
5
 
6
- In this guide, we will need an OpenSearch cluster with more than one node. Let's use the sample [docker-compose.yml](https://opensearch.org/samples/docker-compose.yml) to start a cluster with two nodes. The cluster's API will be available at `localhost:9200` with basic authentication enabled with default username and password of `admin:admin`.
7
-
8
- To start the cluster, run the following command:
9
-
10
- ```bash
11
- cd /path/to/docker-compose.yml
12
- docker-compose up -d
13
- ```
14
-
15
- Let's create a client instance to access this cluster:
6
+ Let's create a client instance to access an OpenSearch cluster:
16
7
 
17
8
  ```javascript
18
9
  const { Client } = require('@opensearch-project/opensearch');
19
10
 
20
11
  const client = new Client({
21
- node: 'https://admin:admin@localhost:9200',
22
- ssl: { rejectUnauthorized: false }
12
+ node: 'http://localhost:9200',
23
13
  });
24
14
 
25
15
  client.info().then(response => {
package/guides/json.md CHANGED
@@ -7,14 +7,7 @@ First, create a client instance with the following code to interact with an Open
7
7
 
8
8
  ```javascript
9
9
  const client = new Client({
10
- ssl: {
11
- rejectUnauthorized: false,
12
- },
13
- node: 'https://localhost:9200',
14
- auth: {
15
- username: 'admin',
16
- password: 'admin',
17
- },
10
+ node: 'http://localhost:9200',
18
11
  });
19
12
  ```
20
13
 
package/guides/msearch.md CHANGED
@@ -5,18 +5,8 @@ OpenSearch's Multi-Search (`msearch`) API allows you to execute multiple search
5
5
  # Setup
6
6
 
7
7
  ```javascript
8
- const host = "localhost";
9
- const protocol = "https";
10
- const port = 9200;
11
- const auth = "admin:admin";
12
- const ca_certs_path = "/full/path/to/root-ca.pem";
13
- const { Client } = require("@opensearch-project/opensearch");
14
- const fs = require("fs");
15
8
  const client = new Client({
16
- node: `${protocol}://${auth}@${host}:${port}`,
17
- ssl: {
18
- ca: fs.readFileSync(ca_certs_path),
19
- },
9
+ node: 'http://localhost:9200',
20
10
  });
21
11
 
22
12
  await client.bulk({
package/guides/search.md CHANGED
@@ -3,28 +3,8 @@ OpenSearch provides a powerful search API that allows you to search for document
3
3
  # Setup
4
4
  Let's start by creating an index and adding some documents to it:
5
5
  ```javascript
6
- var host = "localhost";
7
- var protocol = "https";
8
- var port = 9200;
9
- var auth = "admin:admin"; // For testing only. Don't store credentials in code.
10
- var ca_certs_path = "/full/path/to/root-ca.pem";
11
-
12
- // Optional client certificates if you don't want to use HTTP basic authentication.
13
- // var client_cert_path = '/full/path/to/client.pem'
14
- // var client_key_path = '/full/path/to/client-key.pem'
15
-
16
- // Create a client with SSL/TLS enabled.
17
- var { Client } = require("@opensearch-project/opensearch");
18
- var fs = require("fs");
19
- var client = new Client({
20
- node: protocol + "://" + auth + "@" + host + ":" + port,
21
- ssl: {
22
- ca: fs.readFileSync(ca_certs_path),
23
- // You can turn off certificate verification (rejectUnauthorized: false) if you're using
24
- // self-signed certificates with a hostname mismatch.
25
- // cert: fs.readFileSync(client_cert_path),
26
- // key: fs.readFileSync(client_key_path)
27
- },
6
+ const client = new Client({
7
+ node: 'http://localhost:9200',
28
8
  });
29
9
 
30
10
  await client.indices.create({index: 'movies'});
@@ -120,24 +100,27 @@ const page_1 = await client.search({
120
100
  size: 2,
121
101
  body: search_body
122
102
  });
103
+ const documents_1 = page_1.body.hits.hits;
123
104
 
124
105
  const page_2 = await client.search({
125
106
  index: 'movies',
126
107
  size: 2,
127
108
  body: {
128
109
  ...search_body,
129
- search_after: page_1[page_1.length - 1].sort
110
+ search_after: documents_1[documents_1.length - 1].sort
130
111
  }
131
112
  });
113
+ const documents_2 = page_2.body.hits.hits;
132
114
 
133
115
  const page_3 = await client.search({
134
116
  index: 'movies',
135
117
  size: 2,
136
118
  body: {
137
119
  ...search_body,
138
- search_after: page_2[page_2.length - 1].sort
120
+ search_after: documents_2[documents_2.length - 1].sort
139
121
  }
140
- })
122
+ });
123
+ const documents_3 = page_3.body.hits.hits;
141
124
  ```
142
125
  ### Pagination with scroll
143
126
  When retrieving large amounts of non-real-time data, you can use the `scroll` parameter to paginate through the search results.
@@ -182,25 +165,28 @@ const page_1 = await client.search({
182
165
  size: 2,
183
166
  body: pit_search_body
184
167
  });
185
- console.log(page_1.body.hits.hits);
168
+ const documents_1 = page_1.body.hits.hits;
169
+ console.log(documents_1);
186
170
 
187
171
  const page_2 = await client.search({
188
172
  size: 2,
189
173
  body: {
190
174
  ...pit_search_body,
191
- search_after: page_1[page_1.length - 1].sort
175
+ search_after: documents_1[documents_1.length - 1].sort
192
176
  }
193
177
  });
194
- console.log(page_2.body.hits.hits);
178
+ const documents_2 = page_2.body.hits.hits;
179
+ console.log(documents_2);
195
180
 
196
181
  const page_3 = await client.search({
197
182
  size: 2,
198
183
  body: {
199
184
  ...pit_search_body,
200
- search_after: page2[page_2.length-1].sort
185
+ search_after: documents_2[documents_2.length-1].sort
201
186
  }
202
187
  });
203
- console.log(page_3.body.hits.hits);
188
+ const documents_3 = page_3.body.hits.hits;
189
+ console.log(documents_3);
204
190
 
205
191
  /** Print out the titles of the first 3 pages of results */
206
192
  console.log(page_1.map(hit => hit._source.title));
package/index.d.ts CHANGED
@@ -54,6 +54,7 @@ import {
54
54
  CloudConnectionPool,
55
55
  ResurrectEvent,
56
56
  BasicAuth,
57
+ AwsSigv4Auth,
57
58
  } from './lib/pool';
58
59
  import Serializer from './lib/Serializer';
59
60
  import Helpers from './lib/Helpers';
@@ -126,7 +127,7 @@ interface ClientOptions {
126
127
  opaqueIdPrefix?: string;
127
128
  generateRequestId?: generateRequestIdFn;
128
129
  name?: string | symbol;
129
- auth?: BasicAuth;
130
+ auth?: BasicAuth | AwsSigv4Auth;
130
131
  context?: Context;
131
132
  proxy?: string | URL;
132
133
  enableMetaHeader?: boolean;
package/index.js CHANGED
@@ -192,6 +192,7 @@ class Client extends OpenSearchAPI {
192
192
  opaqueIdPrefix: options.opaqueIdPrefix,
193
193
  context: options.context,
194
194
  memoryCircuitBreaker: options.memoryCircuitBreaker,
195
+ auth: options.auth,
195
196
  });
196
197
 
197
198
  this.helpers = new Helpers({
@@ -32,7 +32,7 @@
32
32
  import { URL } from 'url';
33
33
  import { inspect, InspectOptions } from 'util';
34
34
  import { Readable as ReadableStream } from 'stream';
35
- import { BasicAuth } from './pool';
35
+ import { BasicAuth, AwsSigv4Auth } from './pool';
36
36
  import * as http from 'http';
37
37
  import * as https from 'https';
38
38
  import * as hpagent from 'hpagent';
@@ -48,7 +48,7 @@ export interface ConnectionOptions {
48
48
  agent?: AgentOptions | agentFn;
49
49
  status?: string;
50
50
  roles?: ConnectionRoles;
51
- auth?: BasicAuth;
51
+ auth?: BasicAuth | AwsSigv4Auth;
52
52
  proxy?: string | URL;
53
53
  }
54
54
 
@@ -30,7 +30,7 @@
30
30
  import { Readable as ReadableStream } from 'stream';
31
31
  import Connection from './Connection';
32
32
  import * as errors from './errors';
33
- import { CloudConnectionPool, ConnectionPool } from './pool';
33
+ import { CloudConnectionPool, ConnectionPool, BasicAuth, AwsSigv4Auth } from './pool';
34
34
  import Serializer from './Serializer';
35
35
 
36
36
  export type ApiError =
@@ -82,6 +82,7 @@ interface TransportOptions {
82
82
  name?: string;
83
83
  opaqueIdPrefix?: string;
84
84
  memoryCircuitBreaker?: MemoryCircuitBreakerOptions;
85
+ auth?: BasicAuth | AwsSigv4Auth;
85
86
  }
86
87
 
87
88
  export interface RequestEvent<TResponse = Record<string, any>, TContext = Context> {
package/lib/Transport.js CHANGED
@@ -101,6 +101,7 @@ class Transport {
101
101
  this._sniffEnabled = typeof this.sniffInterval === 'number';
102
102
  this._nextSniff = this._sniffEnabled ? Date.now() + this.sniffInterval : 0;
103
103
  this._isSniffing = false;
104
+ this._auth = opts.auth;
104
105
 
105
106
  if (opts.sniffOnStart === true) {
106
107
  // timer needed otherwise it will clash
@@ -495,6 +496,9 @@ class Transport {
495
496
  Object.assign({}, params.querystring, options.querystring)
496
497
  );
497
498
  }
499
+ if (this._auth !== null && typeof this._auth === 'object' && 'credentials' in this._auth) {
500
+ params.auth = this._auth;
501
+ }
498
502
 
499
503
  // handles request timeout
500
504
  params.timeout = toMs(options.requestTimeout || this.requestTimeout);
@@ -79,6 +79,18 @@ function AwsSigv4Signer(opts = {}) {
79
79
  request.region = opts.region;
80
80
  request.headers = request.headers || {};
81
81
  request.headers['host'] = request.hostname;
82
+
83
+ if (request['auth']) {
84
+ const awssigv4Cred = request['auth'];
85
+ credentialsState.credentials = {
86
+ accessKeyId: awssigv4Cred.credentials.accessKeyId,
87
+ secretAccessKey: awssigv4Cred.credentials.secretAccessKey,
88
+ sessionToken: awssigv4Cred.credentials.sessionToken,
89
+ };
90
+ request.region = awssigv4Cred.region;
91
+ request.service = awssigv4Cred.service;
92
+ delete request['auth'];
93
+ }
82
94
  const signed = aws4.sign(request, credentialsState.credentials);
83
95
  signed.headers['x-amz-content-sha256'] = crypto
84
96
  .createHash('sha256')
@@ -38,7 +38,7 @@ interface BaseConnectionPoolOptions {
38
38
  ssl?: SecureContextOptions;
39
39
  agent?: AgentOptions;
40
40
  proxy?: string | URL;
41
- auth?: BasicAuth;
41
+ auth?: BasicAuth | AwsSigv4Auth;
42
42
  emit: (event: string | symbol, ...args: any[]) => boolean;
43
43
  Connection: typeof Connection;
44
44
  }
@@ -62,6 +62,16 @@ interface BasicAuth {
62
62
  password: string;
63
63
  }
64
64
 
65
+ interface AwsSigv4Auth {
66
+ credentials : {
67
+ accessKeyId: string;
68
+ secretAccessKey: string;
69
+ sessionToken: string;
70
+ }
71
+ region: string;
72
+ service: string;
73
+ }
74
+
65
75
  interface resurrectOptions {
66
76
  now?: number;
67
77
  requestId: string;
@@ -85,7 +95,7 @@ declare class BaseConnectionPool {
85
95
  _ssl: SecureContextOptions | null;
86
96
  _agent: AgentOptions | null;
87
97
  _proxy: string | URL;
88
- auth: BasicAuth;
98
+ auth: BasicAuth | AwsSigv4Auth;
89
99
  Connection: typeof Connection;
90
100
  constructor(opts?: BaseConnectionPoolOptions);
91
101
  /**
@@ -235,6 +245,7 @@ export {
235
245
  ConnectionPoolOptions,
236
246
  getConnectionOptions,
237
247
  BasicAuth,
248
+ AwsSigv4Auth,
238
249
  internals,
239
250
  resurrectOptions,
240
251
  ResurrectEvent,
package/lib/tools.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ export function strongPasswordRequired(os_version?: string): boolean;
package/lib/tools.js ADDED
@@ -0,0 +1,21 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ function strongPasswordRequired(os_version = process.env.OPENSEARCH_VERSION) {
12
+ // OpenSearch 2.12.X and later require strong passwords
13
+ if (os_version === undefined)
14
+ throw new Error('OPENSEARCH_VERSION environment variable is not set');
15
+ if (os_version === 'latest') return true;
16
+ const [major, minor] = os_version.split('.');
17
+ if (parseInt(major) > 2) return true;
18
+ return major === '2' && (minor === 'x' || parseInt(minor) >= 12);
19
+ }
20
+
21
+ module.exports = { strongPasswordRequired };
package/package.json CHANGED
@@ -29,7 +29,7 @@
29
29
  }
30
30
  },
31
31
  "homepage": "https://www.opensearch.org/",
32
- "version": "2.5.0",
32
+ "version": "2.6.0",
33
33
  "versionCanary": "7.10.0-canary.6",
34
34
  "keywords": [
35
35
  "opensearch",
package/samples/README.md CHANGED
@@ -1,14 +1,17 @@
1
1
  # OpenSearch JavaScript Samples
2
2
 
3
- Most samples can be run using OpenSearch installed locally with docker.
3
+ The following will set up a single node OpenSearch instance with the default admin password `myStrongPassword123!`, which we will use to instantiate a client in all samples.
4
4
 
5
- ```
5
+ ```shell
6
6
  docker pull opensearchproject/opensearch:latest
7
- docker run -d -p 9200:9200 -p 9600:9600 -e "discovery.type=single-node" opensearchproject/opensearch:latest
7
+ docker run -d -p 9200:9200 -p 9600:9600 \
8
+ -e 'discovery.type=single-node' -e 'OPENSEARCH_INITIAL_ADMIN_PASSWORD=myStrongPassword123!' \
9
+ opensearchproject/opensearch:latest
8
10
  ```
9
11
 
10
12
  ## Run Samples
11
13
 
12
- ```
14
+ To run the `json.js` sample:
15
+ ```shell
13
16
  node json.js
14
17
  ```
@@ -0,0 +1,91 @@
1
+ /*
2
+ * Copyright OpenSearch Contributors
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ *
5
+ * The OpenSearch Contributors require contributions made to
6
+ * this file be licensed under the Apache-2.0 license or a
7
+ * compatible open source license.
8
+ *
9
+ */
10
+
11
+ // For more information on how to make custom HTTP requests, check out: ./guides/bulk.md
12
+
13
+ const { Client } = require('@opensearch-project/opensearch');
14
+
15
+ // Instantiate a client with basic auth as setup in the README.md file
16
+ const client = new Client({
17
+ ssl: {
18
+ rejectUnauthorized: false,
19
+ },
20
+ node: 'https://localhost:9200',
21
+ auth: {
22
+ username: 'admin',
23
+ password: 'myStrongPassword123!',
24
+ },
25
+ });
26
+
27
+ const start = async () => {
28
+ const movies = 'movies';
29
+ const books = 'books';
30
+
31
+ if ((await client.indices.exists({ index: movies })).body)
32
+ await client.indices.delete({ index: movies });
33
+ if ((await client.indices.exists({ index: books })).body)
34
+ await client.indices.delete({ index: books });
35
+
36
+ await client.indices.create({ index: movies });
37
+ await client.indices.create({ index: books });
38
+
39
+ client
40
+ .bulk({
41
+ index: movies,
42
+ body: [
43
+ { create: {} },
44
+ { title: 'Beauty and the Beast', year: 2030, director: 'Ella' },
45
+ { index: {} },
46
+ { title: 'Snow White', year: 2031, director: 'Jake' },
47
+ { create: {} },
48
+ { title: 'Cinderella', year: 2032, director: 'Clyde' },
49
+ ],
50
+ })
51
+ .then((response) => {
52
+ console.log(response.body.items);
53
+ });
54
+
55
+ client
56
+ .bulk({
57
+ index: movies,
58
+ body: [
59
+ { create: { _id: 1 } },
60
+ { title: 'Beauty and the Beast 1', year: 2050 },
61
+ { delete: { _id: 1 } },
62
+ { create: { _id: 2 } },
63
+ { title: 'Beauty and the Beast 2', year: 2051 },
64
+ { create: {} },
65
+ { title: 'Beauty and the Beast 2', year: 2051 },
66
+ { create: { _index: books } },
67
+ { title: '2012', year: 2012 },
68
+ ],
69
+ })
70
+ .then((response) => {
71
+ console.log(response.body.items);
72
+ });
73
+
74
+ const docs = [
75
+ { title: 'Beauty and the Beast 1', year: 2050 },
76
+ { title: 'Beauty and the Beast 2', year: 2051 },
77
+ ];
78
+
79
+ client.helpers
80
+ .bulk({
81
+ datasource: docs,
82
+ onDocument(_) {
83
+ return { index: { _index: movies } };
84
+ },
85
+ })
86
+ .then((result) => {
87
+ console.log(result);
88
+ });
89
+ };
90
+
91
+ start().then(() => console.log('done'));
package/samples/json.js CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  const { Client } = require('@opensearch-project/opensearch');
14
14
 
15
- // Instantiate a client with basic auth
15
+ // Instantiate a client with basic auth as setup in the README.md file
16
16
  const client = new Client({
17
17
  ssl: {
18
18
  rejectUnauthorized: false,
@@ -20,7 +20,7 @@ const client = new Client({
20
20
  node: 'https://localhost:9200',
21
21
  auth: {
22
22
  username: 'admin',
23
- password: 'admin',
23
+ password: 'myStrongPassword123!',
24
24
  },
25
25
  });
26
26
 
@@ -9,6 +9,7 @@
9
9
  */
10
10
  const { Client } = require('@opensearch-project/opensearch');
11
11
 
12
+ // Instantiate a client with basic auth as setup in the README.md file
12
13
  const client = new Client({
13
14
  ssl: {
14
15
  rejectUnauthorized: false,
@@ -16,7 +17,7 @@ const client = new Client({
16
17
  node: 'https://localhost:9200',
17
18
  auth: {
18
19
  username: 'admin',
19
- password: 'admin',
20
+ password: 'myStrongPassword123!',
20
21
  },
21
22
  });
22
23
 
package/samples/search.js CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  const { Client } = require('@opensearch-project/opensearch');
11
11
 
12
+ // Instantiate a client with basic auth as setup in the README.md file
12
13
  const client = new Client({
13
14
  ssl: {
14
15
  rejectUnauthorized: false,
@@ -16,7 +17,7 @@ const client = new Client({
16
17
  node: 'https://localhost:9200',
17
18
  auth: {
18
19
  username: 'admin',
19
- password: 'admin',
20
+ password: 'myStrongPassword123!',
20
21
  },
21
22
  });
22
23