Getting started

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.

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

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

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

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");

Sample code

  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 self-signed certificates with a hostname mismatch.
  18. // cert: fs.readFileSync(client_cert_path),
  19. // key: fs.readFileSync(client_key_path)
  20. },
  21. });
  22. async function search() {
  23. // Create an index with non-default settings.
  24. var index_name = "books";
  25. var settings = {
  26. settings: {
  27. index: {
  28. number_of_shards: 4,
  29. number_of_replicas: 3,
  30. },
  31. },
  32. };
  33. var response = await client.indices.create({
  34. index: index_name,
  35. body: settings,
  36. });
  37. console.log("Creating index:");
  38. console.log(response.body);
  39. // Add a document to the index.
  40. var document = {
  41. title: "The Outsider",
  42. author: "Stephen King",
  43. year: "2018",
  44. genre: "Crime fiction",
  45. };
  46. var id = "1";
  47. var response = await client.index({
  48. id: id,
  49. index: index_name,
  50. body: document,
  51. refresh: true,
  52. });
  53. console.log("Adding document:");
  54. console.log(response.body);
  55. // Search for the document.
  56. var query = {
  57. query: {
  58. match: {
  59. title: {
  60. query: "The Outsider",
  61. },
  62. },
  63. },
  64. };
  65. var response = await client.search({
  66. index: index_name,
  67. body: query,
  68. });
  69. console.log("Search results:");
  70. console.log(response.body.hits);
  71. // Delete the document.
  72. var response = await client.delete({
  73. index: index_name,
  74. id: id,
  75. });
  76. console.log("Deleting document:");
  77. console.log(response.body);
  78. // Delete the index.
  79. var response = await client.indices.delete({
  80. index: index_name,
  81. });
  82. console.log("Deleting index:");
  83. console.log(response.body);
  84. }
  85. search().catch(console.log);

Authenticate 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. });

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. });

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. });