Elasticsearch + Nodejs Server Example
We are going to create a node server will acts as middle layer for Elasticsearch server. Before downloading require packages from NPM, we are going to download Elasticsearch executable file.
If you prefer video explanation then you can watch on YouTube (in English or in Hindi).
I'm on my windows machine, so I would download a 64-bit windows' version of Elasticsearch, i.e https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.8.1-windows-x86_64.zip
You are free to download Elasticsearch as per your OS. Instructions would little different based on your OS. So, windows guys, we can extract the zip after our download. Now, we will go to bin folder of it and then run elasticsearch.bat. After few seconds, it will be up and running, then you can browse to http://localhost:9200/ Or you can do curl on PowerShell to see its health =>
curl -X GET "localhost:9200/_cat/health?v&pretty"
We are going to have bulk import a JSON file (accounts.json), which can be downloaded from github/elasticsearch.
Then execute below command:
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"
Now, we got the Elasticsearch server up and running with some data to play around. Lets' create a node server and do some full-text searching.
Create a folder named 'Search service' and open command line to install some NPM packages.
Create a js file name, name it 'server.js'. We will be importing express and creating a route to do full-text search. Write below code in the file.
You can see that we have imported a file 'SearchEngine.js' in the server.js. Lets create the file and import @elastic/elasticsearch and we will using multi_match in qyery params to get desired search result(s). Write below code in the file.
We are all set to start the node server. Open command line and run npm start.
Then you can use any browser or postman to hits an endpoint to do full-text searching. e.g. http://localhost:3333/search/bank/_doc?q=mill
Comments
Post a Comment