JavaScript client

    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.

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

    copy

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

    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

    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-west-2',
    7. service: 'es',
    8. // Must return a Promise that resolve to an AWS.Credentials object.
    9. // This function is used to acquire the credentials when the client start and
    10. // when the credentials are expired.
    11. // The Client will refresh the Credentials only when they are expired.
    12. // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
    13. // Example with AWS SDK V2:
    14. getCredentials: () =>
    15. new Promise((resolve, reject) => {
    16. // Any other method to acquire a new Credentials object can be used.
    17. AWS.config.getCredentials((err, credentials) => {
    18. if (err) {
    19. reject(err);
    20. } else {
    21. resolve(credentials);
    22. }
    23. });
    24. }),
    25. }),
    26. node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL
    27. });

    AWS V2 SDK for Amazon OpenSearch Serverless

    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. service: 'es', // 'aoss' for OpenSearch Serverless
    8. // Must return a Promise that resolve to an AWS.Credentials object.
    9. // This function is used to acquire the credentials when the client start and
    10. // when the credentials are expired.
    11. // The Client will refresh the Credentials only when they are expired.
    12. // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials.
    13. // Example with AWS SDK V3:
    14. getCredentials: () => {
    15. // Any other method to acquire a new Credentials object can be used.
    16. const credentialsProvider = defaultProvider();
    17. return credentialsProvider();
    18. },
    19. }),
    20. node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL
    21. });

    copy

    AWS V3 SDK for Amazon OpenSearch Serverless

    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. service: 'aoss',
    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://xxx.region.aoss.amazonaws.com" // OpenSearch domain URL
    20. });

    copy

    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:

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

    copy

    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