JavaScript client

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. For the client’s complete API documentation and additional examples, see the JS client API documentation.

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

To add the client to your project, install it from npm:

  1. npm install @opensearch-project/opensearch

copy

To install a specific major version of the client, run the following command:

  1. npm install @opensearch-project/opensearch@<version>

copy

If you prefer to add the client manually or just want to examine the source code, see opensearch-js on GitHub.

Then require the client:

  1. const { Client } = require("@opensearch-project/opensearch");

copy

Connecting to OpenSearch

To connect to the default OpenSearch host, create a client object with the address https://localhost:9200 if you are using the Security plugin:

  1. var host = "localhost";
  2. var protocol = "https";
  3. var port = 9200;
  4. var auth = "admin:admin"; // For testing only. Don't store credentials in code.
  5. var ca_certs_path = "/full/path/to/root-ca.pem";
  6. // Optional client certificates if you don't want to use HTTP basic authentication.
  7. // var client_cert_path = '/full/path/to/client.pem'
  8. // var client_key_path = '/full/path/to/client-key.pem'
  9. // Create a client with SSL/TLS enabled.
  10. var { Client } = require("@opensearch-project/opensearch");
  11. var fs = require("fs");
  12. var client = new Client({
  13. node: protocol + "://" + auth + "@" + host + ":" + port,
  14. ssl: {
  15. ca: fs.readFileSync(ca_certs_path),
  16. // You can turn off certificate verification (rejectUnauthorized: false) if you're using
  17. // self-signed certificates with a hostname mismatch.
  18. // cert: fs.readFileSync(client_cert_path),
  19. // key: fs.readFileSync(client_key_path)
  20. },
  21. });

copy

Creating an index

To create an OpenSearch index, use the indices.create() method. You can use the following code to construct a JSON object with custom settings:

  1. var index_name = "books";
  2. var settings = {
  3. settings: {
  4. index: {
  5. number_of_shards: 4,
  6. number_of_replicas: 3,
  7. },
  8. },
  9. };
  10. var response = await client.indices.create({
  11. index: index_name,
  12. body: settings,
  13. });

copy

Indexing a document

You can index a document into OpenSearch using the client’s index method:

  1. var document = {
  2. title: "The Outsider",
  3. author: "Stephen King",
  4. year: "2018",
  5. genre: "Crime fiction",
  6. };
  7. var id = "1";
  8. var response = await client.index({
  9. id: id,
  10. index: index_name,
  11. body: document,
  12. refresh: true,
  13. });

copy

Searching for documents

The easiest way to search for documents is to construct a query string. The following code uses a match query to search for “The Outsider” in the title field:

  1. var query = {
  2. query: {
  3. match: {
  4. title: {
  5. query: "The Outsider",
  6. },
  7. },
  8. },
  9. };
  10. var response = await client.search({
  11. index: index_name,
  12. body: query,
  13. });

copy

Deleting a document

You can delete a document using the client’s delete method:

  1. var response = await client.delete({
  2. index: index_name,
  3. id: id,
  4. });

copy

Deleting an index

You can delete an index using the indices.delete() method:

  1. var response = await client.indices.delete({
  2. index: index_name,
  3. });

copy

Sample program

The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index:

  1. "use strict";
  2. var host = "localhost";
  3. var protocol = "https";
  4. var port = 9200;
  5. var auth = "admin:admin"; // For testing only. Don't store credentials in code.
  6. var ca_certs_path = "/full/path/to/root-ca.pem";
  7. // Optional client certificates if you don't want to use HTTP basic authentication.
  8. // var client_cert_path = '/full/path/to/client.pem'
  9. // var client_key_path = '/full/path/to/client-key.pem'
  10. // Create a client with SSL/TLS enabled.
  11. var { Client } = require("@opensearch-project/opensearch");
  12. var fs = require("fs");
  13. var client = new Client({
  14. node: protocol + "://" + auth + "@" + host + ":" + port,
  15. ssl: {
  16. ca: fs.readFileSync(ca_certs_path),
  17. // You can turn off certificate verification (rejectUnauthorized: false) if you're using
  18. // self-signed certificates with a hostname mismatch.
  19. // cert: fs.readFileSync(client_cert_path),
  20. // key: fs.readFileSync(client_key_path)
  21. },
  22. });
  23. async function search() {
  24. // Create an index with non-default settings.
  25. var index_name = "books";
  26. var settings = {
  27. settings: {
  28. index: {
  29. number_of_shards: 4,
  30. number_of_replicas: 3,
  31. },
  32. },
  33. };
  34. var response = await client.indices.create({
  35. index: index_name,
  36. body: settings,
  37. });
  38. console.log("Creating index:");
  39. console.log(response.body);
  40. // Add a document to the index.
  41. var document = {
  42. title: "The Outsider",
  43. author: "Stephen King",
  44. year: "2018",
  45. genre: "Crime fiction",
  46. };
  47. var id = "1";
  48. var response = await client.index({
  49. id: id,
  50. index: index_name,
  51. body: document,
  52. refresh: true,
  53. });
  54. console.log("Adding document:");
  55. console.log(response.body);
  56. // Search for the document.
  57. var query = {
  58. query: {
  59. match: {
  60. title: {
  61. query: "The Outsider",
  62. },
  63. },
  64. },
  65. };
  66. var response = await client.search({
  67. index: index_name,
  68. body: query,
  69. });
  70. console.log("Search results:");
  71. console.log(response.body.hits);
  72. // Delete the document.
  73. var response = await client.delete({
  74. index: index_name,
  75. id: id,
  76. });
  77. console.log("Deleting document:");
  78. console.log(response.body);
  79. // Delete the index.
  80. var response = await client.indices.delete({
  81. index: index_name,
  82. });
  83. console.log("Deleting index:");
  84. console.log(response.body);
  85. }
  86. search().catch(console.log);

copy

Authenticating with Amazon OpenSearch Service – AWS Sigv4

Use the following code to authenticate with AWS V2 SDK:

  1. const AWS = require('aws-sdk'); // V2 SDK.
  2. const { Client } = require('@opensearch-project/opensearch');
  3. const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
  4. const client = new Client({
  5. ...AwsSigv4Signer({
  6. region: 'us-east-1',
  7. // Must return a Promise that resolve to an AWS.Credentials object.
  8. // This function is used to acquire the credentials when the client start and
  9. // when the credentials are expired.
  10. // The Client will refresh the Credentials only when they are expired.
  11. // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
  12. // Example with AWS SDK V2:
  13. getCredentials: () =>
  14. new Promise((resolve, reject) => {
  15. // Any other method to acquire a new Credentials object can be used.
  16. AWS.config.getCredentials((err, credentials) => {
  17. if (err) {
  18. reject(err);
  19. } else {
  20. resolve(credentials);
  21. }
  22. });
  23. }),
  24. }),
  25. node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
  26. });

copy

Use the following code to authenticate with AWS V3 SDK:

  1. const { defaultProvider } = require("@aws-sdk/credential-provider-node"); // V3 SDK.
  2. const { Client } = require('@opensearch-project/opensearch');
  3. const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws');
  4. const client = new Client({
  5. ...AwsSigv4Signer({
  6. region: 'us-east-1',
  7. // Must return a Promise that resolve to an AWS.Credentials object.
  8. // This function is used to acquire the credentials when the client start and
  9. // when the credentials are expired.
  10. // The Client will refresh the Credentials only when they are expired.
  11. // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
  12. // Example with AWS SDK V3:
  13. getCredentials: () => {
  14. // Any other method to acquire a new Credentials object can be used.
  15. const credentialsProvider = defaultProvider();
  16. return credentialsProvider();
  17. },
  18. }),
  19. node: "https://search-xxx.region.es.amazonaws.com", // OpenSearch domain URL
  20. });

copy

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:

  1. var client = new Client({
  2. memoryCircuitBreaker: {
  3. enabled: true,
  4. maxPercentage: 0.8,
  5. },
  6. });

copy