OpenSearch with JavaScript Mastery
OpenSearch Setup
Getting Started with JavaScript
To connect your JavaScript application to an OpenSearch cluster, you need an official client library. This library handles the communication, making it much easier to send requests and receive responses. We'll assume you already have an OpenSearch cluster running and accessible.
Installing the Client
The first step is to add the OpenSearch JavaScript client to your project. You can install it using either npm or yarn. This package contains all the necessary tools to interact with your cluster's API.
# Using npm
npm install @opensearch-project/opensearch
# Or using yarn
yarn add @opensearch-project/opensearch
Connecting to Your Cluster
Once the package is installed, you can configure the client to connect to your OpenSearch instance. You'll need the cluster's endpoint URL and authentication credentials. The endpoint typically includes the protocol, host, and port, like https://localhost:9200.
Start by importing the Client class from the package. Then, create a new instance of the client, passing in your connection details.
import { Client } from '@opensearch-project/opensearch';
const client = new Client({
node: 'https://admin:admin@localhost:9200',
ssl: {
// Set to false for self-signed certificates in a development environment
rejectUnauthorized: false
}
});
This client object is now your gateway to OpenSearch. You'll use it for all subsequent operations, like managing indices and documents.
Creating an Index
An index is like a database table in a traditional database. It's a logical namespace that holds a collection of related documents. Before you can add any data, you need to create an index.
Let's create an index named movies. We'll use the indices.create() method. This method is asynchronous, so we use await to wait for the operation to complete.
async function createMoviesIndex() {
try {
const response = await client.indices.create({
index: 'movies',
});
console.log('Index created:', response.body);
} catch (error) {
console.error('Error creating index:', error);
}
}
createMoviesIndex();
If the index already exists, this function will throw an error. A robust application would first check if the index exists using client.indices.exists().
Adding Documents
With our movies index ready, we can start adding documents. A document is a JSON object that represents a single item in your index. Each document has a unique ID. If you don't provide one, OpenSearch will generate it for you.
We'll use the index() method to add a document. This single method can either create a new document or update an existing one with the same ID.
async function addDocument() {
try {
const response = await client.index({
id: '1', // The document's unique ID
index: 'movies', // The index to add the document to
body: { // The actual data
title: 'The Fellowship of the Ring',
director: 'Peter Jackson',
year: 2001,
},
refresh: true, // Make the document immediately searchable
});
console.log('Document added:', response.body);
} catch (error) {
console.error('Error adding document:', error);
}
}
addDocument();
The
refresh: trueparameter tells OpenSearch to make this new document available for searching right away. By default, there's a slight delay. It's useful for testing but can impact performance if used for every write operation in a busy system.
Executing a Basic Search
Now for the main event: searching. Let's find movies directed by 'Peter Jackson'. We'll use the search() method and provide a query body.
The match query is a standard full-text query. It looks for the specified text in a particular field. The results, or 'hits', will be returned in the response body.
async function searchMovies() {
try {
const response = await client.search({
index: 'movies',
body: {
query: {
match: {
director: 'Peter Jackson',
},
},
},
});
console.log('Search results:', response.body.hits.hits);
} catch (error) {
console.error('Error searching:', error);
}
}
searchMovies();
The search results are nested inside response.body.hits.hits. This array contains all the documents that matched your query, along with metadata like the relevance score for each result.
What is the first step to connect a JavaScript application to an OpenSearch cluster?
When instantiating the OpenSearch JavaScript client, which piece of information is essential for establishing the connection?
You've now connected your JavaScript application to OpenSearch, created an index, added a document, and performed a basic search. These are the fundamental building blocks for creating powerful search experiences.