@opensearch-project/opensearch 2.2.0 → 2.2.1

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.
@@ -0,0 +1,217 @@
1
+ # Search
2
+ OpenSearch provides a powerful search API that allows you to search for documents in an index. The search API supports a number of parameters that allow you to customize the search operation. In this guide, we will explore the search API and its parameters.
3
+ # Setup
4
+ Let's start by creating an index and adding some documents to it:
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
+ },
28
+ });
29
+
30
+ await client.indices.create({index: 'movies'});
31
+
32
+ for(let i = 0; i < 10; i++) {
33
+ await client.index({
34
+ index: 'movies',
35
+ id: i,
36
+ body: {
37
+ title: `The Dark Knight ${i}`,
38
+ director: 'Christopher Nolan',
39
+ year: 2008 + i
40
+ }
41
+ });
42
+ }
43
+
44
+ await client.index({
45
+ index: 'movies',
46
+ body: {
47
+ title: 'The Godfather',
48
+ director: 'Francis Ford Coppola',
49
+ year: 1972
50
+ }
51
+ });
52
+
53
+ await client.index({
54
+ index: 'movies',
55
+ body: {
56
+ title: 'The Shawshank Redemption',
57
+ director: 'Frank Darabont',
58
+ year: 1994
59
+ }
60
+ });
61
+
62
+ await client.index({index: 'movies', refresh: true});
63
+ ```
64
+ # Search API
65
+ ### Basic Search
66
+ The search API allows you to search for documents in an index. The following example searches for ALL documents in the movies index:
67
+
68
+ ```javascript
69
+ const response = await client.search({
70
+ index: 'movies'
71
+ });
72
+ ```
73
+ You can also search for documents that match a specific query. The following example searches for documents that match the query `dark knight`:
74
+ ```javascript
75
+ const response = await client.search({
76
+ index: 'movies',
77
+ body: {
78
+ query: {
79
+ match: {
80
+ title: 'dark knight'
81
+ }
82
+ }
83
+ }
84
+ });
85
+ console.log(response.body.hits.hits);
86
+ ```
87
+
88
+ OpenSearch query DSL allows you to specify complex queries. Check out the [OpenSearch query DSL documentation](https://opensearch.org/docs/latest/query-dsl/) for more information.
89
+
90
+ ### Basic Pagination
91
+ The search API allows you to paginate through the search results. The following example searches for documents that match the query `dark knight`, sorted by `year` in ascending order, and returns the first 2 results after skipping the first 5 results:
92
+ ```javascript
93
+ search_body = {
94
+ query: {
95
+ match: {
96
+ title: 'dark knight'
97
+ }
98
+ },
99
+ sort: [
100
+ {
101
+ year: {
102
+ order: 'asc'
103
+ }
104
+ }
105
+ ]
106
+ }
107
+
108
+ await client.search({
109
+ index: 'movies',
110
+ size: 2,
111
+ from: 5,
112
+ body: search_body
113
+ });
114
+ ```
115
+
116
+ With sorting, you can also use the `search_after` parameter to paginate through the search results. Let's say you have already displayed the first page of results, and you want to display the next page. You can use the `search_after` parameter to paginate through the search results. The following example will demonstrate how to get the first 3 pages of results using the search query of the previous example:
117
+ ```javascript
118
+ const page_1 = await client.search({
119
+ index: 'movies',
120
+ size: 2,
121
+ body: search_body
122
+ });
123
+
124
+ const page_2 = await client.search({
125
+ index: 'movies',
126
+ size: 2,
127
+ body: {
128
+ ...search_body,
129
+ search_after: page_1[page_1.length - 1].sort
130
+ }
131
+ });
132
+
133
+ const page_3 = await client.search({
134
+ index: 'movies',
135
+ size: 2,
136
+ body: {
137
+ ...search_body,
138
+ search_after: page_2[page_2.length - 1].sort
139
+ }
140
+ })
141
+ ```
142
+ ### Pagination with scroll
143
+ When retrieving large amounts of non-real-time data, you can use the `scroll` parameter to paginate through the search results.
144
+ ```javascript
145
+ const page_1 = await client.search({
146
+ index: 'movies',
147
+ scroll: '1m',
148
+ size: 2,
149
+ body: search_body
150
+ });
151
+
152
+ const page_2 = await client.scroll({
153
+ scroll_id: page_1._scroll_id,
154
+ scroll: '1m'
155
+ });
156
+
157
+ const page_3 = await client.scroll({
158
+ scroll_id: page_2._scroll_id,
159
+ scroll: '1m'
160
+ });
161
+ ```
162
+ ### Pagination with point in time
163
+ The scroll example above has one weakness: if the index is updated while you are scrolling through the results, they will be paginated inconsistently. To avoid this, you should use the "Point in Time" feature. The following example demonstrates how to use the `point_in_time` and `pit_id` parameters to paginate through the search results:
164
+ ```javascript
165
+ /** Create a point in time */
166
+ const pit = client.create_pit({
167
+ index: 'movies',
168
+ keep_alive: '1m'
169
+ });
170
+
171
+ /** Include pit info in the search body */
172
+ const pit_search_body = {
173
+ ..search_body,
174
+ pit: {
175
+ id: pit.pit_id,
176
+ keep_alive: '1m'
177
+ }
178
+ }
179
+
180
+ /** Get the first 3 pages of results */
181
+ const page_1 = await client.search({
182
+ size: 2,
183
+ body: pit_search_body
184
+ });
185
+ console.log(page_1.body.hits.hits);
186
+
187
+ const page_2 = await client.search({
188
+ size: 2,
189
+ body: {
190
+ ...pit_search_body,
191
+ search_after: page_1[page_1.length - 1].sort
192
+ }
193
+ });
194
+ console.log(page_2.body.hits.hits);
195
+
196
+ const page_3 = await client.search({
197
+ size: 2,
198
+ body: {
199
+ ...pit_search_body,
200
+ search_after: page2[page_2.length-1].sort
201
+ }
202
+ });
203
+ console.log(page_3.body.hits.hits);
204
+
205
+ /** Print out the titles of the first 3 pages of results */
206
+ console.log(page_1.map(hit => hit._source.title));
207
+ console.log(page_2.map(hit => hit._source.title));
208
+ console.log(page_3.map(hit => hit._source.title));
209
+
210
+ /** Delete the point in time */
211
+ client.delete_pit({body: {pit_id: pit.pit_id}});
212
+ ```
213
+ Note that a point-in-time is associated with an index or a set of index. So, when performing a search with a point-in-time, you DO NOT specify the index in the search.
214
+ # Cleanup
215
+ ```javascript
216
+ await client.indices.delete({index: 'movies'});
217
+ ```
package/lib/Connection.js CHANGED
@@ -134,7 +134,7 @@ class Connection {
134
134
  request.once('error', () => {}); // we need to catch the request aborted error
135
135
  debug('Request aborted', params);
136
136
  this._openRequests--;
137
- callback(new RequestAbortedError(), null);
137
+ callback(new RequestAbortedError('Request aborted'), null);
138
138
  };
139
139
 
140
140
  request.on('response', onResponse);
package/lib/Serializer.js CHANGED
@@ -69,7 +69,7 @@ class Serializer {
69
69
  ndserialize(array) {
70
70
  debug('ndserialize', array);
71
71
  if (Array.isArray(array) === false) {
72
- throw new SerializationError('The argument provided is not an array');
72
+ throw new SerializationError('The argument provided is not an array', array);
73
73
  }
74
74
  let ndjson = '';
75
75
  for (let i = 0, len = array.length; i < len; i++) {
@@ -19,6 +19,7 @@ import { OpenSearchClientError } from '../errors';
19
19
  interface AwsSigv4SignerOptions {
20
20
  getCredentials?: () => Promise<Credentials>;
21
21
  region: string;
22
+ service?: 'es' | 'aoss';
22
23
  }
23
24
 
24
25
  interface AwsSigv4SignerResponse {
package/lib/errors.d.ts CHANGED
@@ -51,7 +51,7 @@ export declare class ConnectionError<
51
51
  name: string;
52
52
  message: string;
53
53
  meta: ApiResponse<TResponse, TContext>;
54
- constructor(message: string, meta: ApiResponse);
54
+ constructor(message: string, meta?: ApiResponse);
55
55
  }
56
56
 
57
57
  export declare class NoLivingConnectionsError<
@@ -104,7 +104,7 @@ export declare class RequestAbortedError<
104
104
  name: string;
105
105
  message: string;
106
106
  meta: ApiResponse<TResponse, TContext>;
107
- constructor(message: string, meta: ApiResponse);
107
+ constructor(message: string, meta?: ApiResponse);
108
108
  }
109
109
 
110
110
  export declare class NotCompatibleError<
package/lib/errors.js CHANGED
@@ -70,7 +70,7 @@ class NoLivingConnectionsError extends OpenSearchClientError {
70
70
 
71
71
  class SerializationError extends OpenSearchClientError {
72
72
  constructor(message, data) {
73
- super(message, data);
73
+ super(message);
74
74
  Error.captureStackTrace(this, SerializationError);
75
75
  this.name = 'SerializationError';
76
76
  this.message = message || 'Serialization Error';
@@ -80,7 +80,7 @@ class SerializationError extends OpenSearchClientError {
80
80
 
81
81
  class DeserializationError extends OpenSearchClientError {
82
82
  constructor(message, data) {
83
- super(message, data);
83
+ super(message);
84
84
  Error.captureStackTrace(this, DeserializationError);
85
85
  this.name = 'DeserializationError';
86
86
  this.message = message || 'Deserialization Error';
@@ -32,6 +32,7 @@
32
32
  const { URL } = require('url');
33
33
  const debug = require('debug')('opensearch');
34
34
  const Connection = require('../Connection');
35
+ const { ConfigurationError } = require('../errors');
35
36
  const noop = () => {};
36
37
 
37
38
  class BaseConnectionPool {
@@ -64,6 +65,9 @@ class BaseConnectionPool {
64
65
  * Creates a new connection instance.
65
66
  */
66
67
  createConnection(opts) {
68
+ if (opts instanceof Connection) {
69
+ throw new ConfigurationError('The argument provided is already a Connection instance.');
70
+ }
67
71
  if (typeof opts === 'string') {
68
72
  opts = this.urlToHost(opts);
69
73
  }
@@ -102,18 +106,25 @@ class BaseConnectionPool {
102
106
  */
103
107
  addConnection(opts) {
104
108
  if (Array.isArray(opts)) {
105
- return opts.forEach((o) => this.addConnection(o));
109
+ opts.forEach((o) => this.addConnection(o));
110
+ return;
106
111
  }
107
-
108
112
  if (typeof opts === 'string') {
109
113
  opts = this.urlToHost(opts);
110
114
  }
111
115
 
112
- const connectionById = this.connections.find((c) => c.id === opts.id);
113
- const connectionByUrl = this.connections.find((c) => c.id === opts.url.href);
116
+ const connectionId = opts.id;
117
+ const connectionUrl = opts.url.href;
118
+
119
+ if (connectionId || connectionUrl) {
120
+ const connectionById = this.connections.find((c) => c.id === connectionId);
121
+ const connectionByUrl = this.connections.find((c) => c.id === connectionUrl);
114
122
 
115
- if (connectionById || connectionByUrl) {
116
- throw new Error(`Connection with id '${opts.id || opts.url.href}' is already present`);
123
+ if (connectionById || connectionByUrl) {
124
+ throw new ConfigurationError(
125
+ `Connection with id '${connectionId || connectionUrl}' is already present`
126
+ );
127
+ }
117
128
  }
118
129
 
119
130
  this.update([...this.connections, opts]);
@@ -133,10 +144,8 @@ class BaseConnectionPool {
133
144
 
134
145
  /**
135
146
  * Empties the connection pool.
136
- *
137
- * @returns {ConnectionPool}
138
147
  */
139
- empty(callback) {
148
+ empty(callback = noop) {
140
149
  debug('Emptying the connection pool');
141
150
  let openConnections = this.size;
142
151
  this.connections.forEach((connection) => {
@@ -30,6 +30,7 @@
30
30
  'use strict';
31
31
 
32
32
  const BaseConnectionPool = require('./BaseConnectionPool');
33
+ const noop = () => {};
33
34
 
34
35
  class CloudConnectionPool extends BaseConnectionPool {
35
36
  constructor(opts) {
@@ -49,9 +50,8 @@ class CloudConnectionPool extends BaseConnectionPool {
49
50
  /**
50
51
  * Empties the connection pool.
51
52
  *
52
- * @returns {ConnectionPool}
53
53
  */
54
- empty(callback) {
54
+ empty(callback = noop) {
55
55
  super.empty(() => {
56
56
  this.cloudConnection = null;
57
57
  callback();
@@ -73,7 +73,7 @@ class ConnectionPool extends BaseConnectionPool {
73
73
 
74
74
  /**
75
75
  * Marks a connection as 'dead'.
76
- * If needed adds the connection to the dead list
76
+ * If needed, adds the connection to the dead list
77
77
  * and then increments the `deadCount`.
78
78
  *
79
79
  * @param {object} connection
@@ -82,9 +82,9 @@ class ConnectionPool extends BaseConnectionPool {
82
82
  const { id } = connection;
83
83
  debug(`Marking as 'dead' connection '${id}'`);
84
84
  if (this.dead.indexOf(id) === -1) {
85
- // It might happen that `markDead` is called jsut after
85
+ // It might happen that `markDead` is called just after
86
86
  // a pool update, and in such case we will add to the dead
87
- // list a node that no longer exist. The following check verify
87
+ // list a node that no longer exists. The following check verifies
88
88
  // that the connection is still part of the pool before
89
89
  // marking it as dead.
90
90
  for (let i = 0; i < this.size; i++) {
@@ -227,7 +227,7 @@ class ConnectionPool extends BaseConnectionPool {
227
227
  *
228
228
  * @returns {ConnectionPool}
229
229
  */
230
- empty(callback) {
230
+ empty(callback = noop) {
231
231
  super.empty(() => {
232
232
  this.dead = [];
233
233
  callback();
@@ -31,7 +31,7 @@
31
31
 
32
32
  import { URL } from 'url';
33
33
  import { SecureContextOptions } from 'tls';
34
- import Connection, { AgentOptions } from '../Connection';
34
+ import Connection, { AgentOptions, ConnectionOptions } from '../Connection';
35
35
  import { nodeFilterFn, nodeSelectorFn } from '../Transport';
36
36
 
37
37
  interface BaseConnectionPoolOptions {
@@ -115,13 +115,20 @@ declare class BaseConnectionPool {
115
115
  * @returns {object|null} connection
116
116
  */
117
117
  getConnection(opts?: getConnectionOptions): Connection | null;
118
+
119
+ /**
120
+ * Creates a new connection instance.
121
+ * @param {object|string} opts
122
+ * @returns {Connection}
123
+ */
124
+ createConnection(opts: ConnectionOptions | string): Connection;
118
125
  /**
119
126
  * Adds a new connection to the pool.
120
127
  *
121
128
  * @param {object|string} host
122
129
  * @returns {ConnectionPool}
123
130
  */
124
- addConnection(opts: any): Connection;
131
+ addConnection(opts: string | ConnectionOptions | ConnectionOptions[]): Connection;
125
132
  /**
126
133
  * Removes a new connection to the pool.
127
134
  *
@@ -132,16 +139,15 @@ declare class BaseConnectionPool {
132
139
  /**
133
140
  * Empties the connection pool.
134
141
  *
135
- * @returns {ConnectionPool}
136
142
  */
137
- empty(): this;
143
+ empty(callback?: () => void): void;
138
144
  /**
139
145
  * Update the ConnectionPool with new connections.
140
146
  *
141
147
  * @param {array} array of connections
142
148
  * @returns {ConnectionPool}
143
149
  */
144
- update(connections: any[]): this;
150
+ update(connections: Connection[]): this;
145
151
  /**
146
152
  * Transforms the nodes objects to a host object.
147
153
  *
@@ -155,7 +161,7 @@ declare class BaseConnectionPool {
155
161
  * @param {string} url
156
162
  * @returns {object} host
157
163
  */
158
- urlToHost(url: string): { url: URL };
164
+ urlToHost(url: string): ConnectionOptions;
159
165
  }
160
166
 
161
167
  declare class ConnectionPool extends BaseConnectionPool {
@@ -183,12 +189,35 @@ declare class ConnectionPool extends BaseConnectionPool {
183
189
  opts: resurrectOptions,
184
190
  callback?: (isAlive: boolean | null, connection: Connection | null) => void
185
191
  ): void;
192
+
193
+ /**
194
+ * Empties the connection pool.
195
+ */
196
+ empty(callback?: () => void): void;
197
+ /**
198
+ * Update the ConnectionPool with new connections.
199
+ *
200
+ * @param {array} array of connections
201
+ * @returns {ConnectionPool}
202
+ */
203
+ update(connections: Connection[]): this;
186
204
  }
187
205
 
188
206
  declare class CloudConnectionPool extends BaseConnectionPool {
189
207
  cloudConnection: Connection | null;
190
208
  constructor(opts?: BaseConnectionPoolOptions);
191
209
  getConnection(): Connection | null;
210
+ /**
211
+ * Empties the connection pool.
212
+ */
213
+ empty(callback?: () => void): void;
214
+ /**
215
+ * Update the ConnectionPool with new connections.
216
+ *
217
+ * @param {array} array of connections
218
+ * @returns {ConnectionPool}
219
+ */
220
+ update(connections: Connection[]): this;
192
221
  }
193
222
 
194
223
  declare function defaultNodeFilter(node: Connection): boolean;
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "import": "./index.mjs"
11
11
  },
12
12
  "./aws": "./lib/aws/index.js",
13
- "./": "./"
13
+ "./*": "./*"
14
14
  },
15
15
  "typesVersions": {
16
16
  "*": {
@@ -23,7 +23,7 @@
23
23
  }
24
24
  },
25
25
  "homepage": "https://www.opensearch.org/",
26
- "version": "2.2.0",
26
+ "version": "2.2.1",
27
27
  "versionCanary": "7.10.0-canary.6",
28
28
  "keywords": [
29
29
  "opensearch",
@@ -59,7 +59,7 @@
59
59
  "@aws-sdk/types": "^3.160.0",
60
60
  "@babel/eslint-parser": "^7.19.1",
61
61
  "@sinonjs/fake-timers": "github:sinonjs/fake-timers#0bfffc1",
62
- "@types/node": "^18.11.18",
62
+ "@types/node": "^18.15.3",
63
63
  "convert-hrtime": "^5.0.0",
64
64
  "cross-zip": "^4.0.0",
65
65
  "dedent": "^0.7.0",
@@ -75,18 +75,18 @@
75
75
  "license-checker": "^25.0.1",
76
76
  "minimist": "^1.2.5",
77
77
  "node-fetch": "^3.2.10",
78
- "ora": "^5.4.0",
78
+ "ora": "^6.1.2",
79
79
  "prettier": "^2.6.2",
80
80
  "pretty-hrtime": "^1.0.3",
81
81
  "proxy": "^1.0.2",
82
- "rimraf": "^4.1.1",
82
+ "rimraf": "^5.0.0",
83
83
  "semver": "^7.3.5",
84
84
  "simple-git": "^3.15.0",
85
85
  "simple-statistics": "^7.7.0",
86
86
  "split2": "^4.1.0",
87
87
  "stoppable": "^1.1.0",
88
88
  "tap": "^16.3.0",
89
- "tsd": "^0.24.1",
89
+ "tsd": "^0.27.0",
90
90
  "workq": "^3.0.0",
91
91
  "xmlbuilder2": "^3.0.2"
92
92
  },