Elasticsearch with the JavaScript client
Uses @elastic/elasticsearch 9.5. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”https://es.example.com:9200https://machnosql.example.com:9200The address comes from the environment variable ELASTICSEARCH_URL, so switching to MachNoSQL changes configuration only.
export ELASTICSEARCH_URL='https://machnosql.example.com:9200'npm installnpm startCredentials come from ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
// Product search on Elasticsearch, unchanged on MachNoSQL.import { Client } from "@elastic/elasticsearch";
const client = new Client({ node: process.env.ELASTICSEARCH_URL, auth: { username: process.env.ELASTICSEARCH_USERNAME, password: process.env.ELASTICSEARCH_PASSWORD },});
if (!(await client.indices.exists({ index: "products" }))) { await client.indices.create({ index: "products", mappings: { properties: { name: { type: "text" }, brand: { type: "keyword" }, price: { type: "float" } } }, });}
await client.helpers.bulk({ datasource: [ { id: "1", name: "mechanical keyboard", brand: "keyco", price: 89.0 }, { id: "2", name: "wireless keyboard", brand: "typer", price: 49.0 }, { id: "3", name: "gaming mouse", brand: "keyco", price: 39.0 }, ], onDocument: ({ id }) => ({ index: { _index: "products", _id: id } }),});await client.indices.refresh({ index: "products" });
const found = await client.search({ index: "products", query: { match: { name: "keyboard" } } });for (const hit of found.hits.hits) { console.log(hit._score, hit._source.name);}
const brands = await client.search({ index: "products", size: 0, aggs: { brands: { terms: { field: "brand" } } } });console.log(brands.aggregations.brands.buckets);{ "name": "machnosql-example-elasticsearch-node", "private": true, "type": "module", "scripts": { "start": "node app.js" }, "dependencies": { "@elastic/elasticsearch": "^9.5.1" }}