Angular 4 ElasticSearch – Quick Start – How to add Elasticsearch.js

In this tutorial, we’re gonna look at how to add ElasticSearch to an Angular 4 Project.

Update (Angular 6 – Elasticsearch 6):
Angular 6 ElasticSearch – Quick Start – How to add Elasticsearch.js

Related Posts:
How to start SpringBoot ElasticSearch using Spring Data
Angular 4 ElasticSearch example – How to create an Index
Angular 4 ElasticSearch example – Add Document to Index
Angular 4 ElasticSearch example – Get All Documents in Index
Angular 4 ElasticSearch example – Documents Pagination with Scroll
Angular 4 ElasticSearch example – simple Full Text Search

** Elasticsearch Tutorials **

I. Install ElasticSearch

Go to ElasticSearch guide – Getting Started » Installation and follow step by step to install ElasticSearch.

Test local install of ElasticSearch
– by command line:
curl -XGET localhost:9200
– or enter http://localhost:9200/ url on your Browser.

The result should be like this:

{
  "name" : "first_node_test",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "E8eoz-uWT0Gxi-ygUIB10Q",
  "version" : {
    "number" : "5.6.2",
    "build_hash" : "57e20f3",
    "build_date" : "2017-09-23T13:16:45.703Z",
    "build_snapshot" : false,
    "lucene_version" : "6.6.1"
  },
  "tagline" : "You Know, for Search"
}

II. Add ElasticSearch to Angular 4 Project

1. Install the type definition

Run command:
npm install --save-dev @types/elasticsearch

You will see an elasticsearch directory in node_modules folder:
angular-4-elasticsearch-example-quick-start-node-modules

2. Add dependency

Open package.json in your Angular 4 Project, add:

...
"dependencies": {
	"elasticsearch": "^13.0.1",
	...
},
...

Re-install your Angular 4 Project:
npm install

III. Use ElasticSearch in Angular 4 Project

1. Import and use
import * as elasticsearch from 'elasticsearch';
//...

  private client: elasticsearch.Client

  private connect() {
    this.client = new elasticsearch.Client({
      host: 'localhost:9200',
      log: 'trace'
    });
  }

or:

import { Client } from 'elasticsearch';
//...

  private client: Client;

  private connect() {
    this.client = new Client({
      host: 'http://localhost:9200',
      log: 'trace'
    });
  }
2. Add CORS config

To work with ElasticSearch, we need to enable CORS by adding in /config/elasticsearch.yml:

http.cors.enabled : true
 
http.cors.allow-origin : "*"
http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length
3. Ping to test

Write the code below to ping to ElasticSearch:

this.client.ping({
  requestTimeout: Infinity,
  body: 'hello JavaSampleApproach!'
});

Open Browser to check, it should be:

TRACE: 2017-10-12T14:48:42Z
  -> HEAD http://localhost:9200/
  hello JavaSampleApproach!
  <- 200

IV. Practice and Source Code

You can find more practice (with source code) such as creating an ElasticSearch Index at:
Angular 4 ElasticSearch example – How to create an Index

19 thoughts on “Angular 4 ElasticSearch – Quick Start – How to add Elasticsearch.js”

  1. I got below error while trying to execute this sample Elastic search (while Clicking Customers button). please help to fix it. so that i can able to understand more clearly.

    TRACE: 2017-12-19T12:16:46Z
      -> POST http://localhost:9200/jsa_customer_idx/customer/_search?scroll=1m&filter_path=hits.hits._source%2Chits.total%2C_scroll_id
      {
        "size": 3,
        "query": {
          "match_all": {}
        },
        "sort": [
          {
            "_uid": {
              "order": "asc"
            }
          }
        ]
      }
      <- 404
      {
        "error": {
          "root_cause": [
            {
              "type": "index_not_found_exception",
              "reason": "no such index",
              "resource.type": "index_or_alias",
              "resource.id": "jsa_customer_idx",
              "index_uuid": "_na_",
              "index": "jsa_customer_idx"
            }
          ],
          "type": "index_not_found_exception",
          "reason": "no such index",
          "resource.type": "index_or_alias",
          "resource.id": "jsa_customer_idx",
          "index_uuid": "_na_",
          "index": "jsa_customer_idx"
        },
        "status": 404
      }
    

    Thanks for guidance.

    1. Hi SeethaPartha,

      You should create jsa_customer_idx Index first.
      The simplest method for creating an index is using Kibana with statement:

      PUT jsa_customer_idx
      {
          "settings" : {
              "index" : {
                  "number_of_shards" : 3, 
                  "number_of_replicas" : 2 
              }
          }
      }
      

      Regards,
      JSA.

      1. Hi, Thanks for that reply.

        Can you please guide me how to do full text search in all fields(More than one field) at a time.

        And also please guide me for doing pagination for this data.

  2. Hi er,

    I’m trying to use es with angular.
    I followed your install guide.
    but when I changed to ‘@^13.0.1’ on package.json
    it said
    No matching version found for @types/elasticsearch@^13.0.1

    could you help me a little more.

      1. I did.
        When I re-installed it says “No matching version found for @types/elasticsearch@^13.0.1”

        I using this plugin with ionic3 which use angular 4.

        so I added typeRoots value in tsconfig.json.

        {
          "compilerOptions": {
            "allowSyntheticDefaultImports": true,
            "declaration": false,
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "lib": [
              "dom",
              "es2016"
            ],
            "module": "es2015",
            "moduleResolution": "node",
            "sourceMap": true,
            "target": "es5",
            "typeRoots": [
              "./node_modules/@types"
            ],
            "baseUrl":"./src",
            "paths":{
              "@app/*": [ "app/*" ],
              "@assets/*": [ "assets/*" ],
              "@env": [ "environments/environment" ],
              "@pages/*": [ "pages/*" ],
              "@providers/*": [ "providers/*" ],
              "@theme/*": [ "theme/*" ]
            }
          },
          "include": [
            "src/**/*.ts"
          ],
          "exclude": [
            "node_modules",
            "src/**/*.spec.ts",
            "src/**/__tests__/*.ts"
          ],
          "compileOnSave": false,
          "atom": {
            "rewriteTsconfig": false
          }
        }
        

        and everything looks fine. but when I serve it

        Uncaught Error: Cannot find module “elasticsearch”

        my elastic-search.ts file.

        import { HttpClient } from '@angular/common/http';
        import { Injectable } from '@angular/core';
        import {Client} from "elasticsearch";
        
        /*
          Generated class for the ElasticSearchProvider provider.
        
          See https://angular.io/guide/dependency-injection for more info on providers
          and Angular DI.
        */
        @Injectable()
        export class ElasticSearchProvider {
        
          constructor(
            public http: HttpClient,
            private client: Client
          ) {
            console.log('Hello ElasticSearchProvider Provider');
            console.log(this.client);
        
          }
        
          isAvailable(): any {
            return this.client.ping({
              requestTimeout: Infinity,
              body: 'hello muchsqaure'
            });
          }
        
        }
        
  3. please can you help me

    i took this:
    IV. Practice and Source Code
    You can find more practice (with source code) such as creating an ElasticSearch Index at:
    Angular 4 ElasticSearch example – How to create an Index

    and i get this : Elasticsearch server status: ERROR

    JavaSampleApproach

    Angular4-SpringBoot Demo

    Elasticsearch server status: ERROR

    while elasticsearch has started i checked at localhost: 9200

    thanks

    1. Hi loulouXX,

      Please make sure that you install Elasticsearch correctly by checking cmd: curl -XGET localhost:9200.
      Then guarantee that CORS configuration is correct with this step: Add CORS config.

      Regards,
      JSA.

  4. Hello this tutorial is excellent to start working with elasticsearch. However, I have a problem when I put my project into production. I understand that the host changes as follows:

    private connect() {
        this.client = new Client({
          host: //'https://my-domain.com/elasticsearch',
          log: 'trace'
        });
      }
    

    In this way, the server runs perfectly (Elasticsearch server status: OK) but when I add a new customer I get the following error:

    o.Serialization {message: “Unable to parse/serialize body”, body: “”, status: 200, stack: “Error: Unable to parse/serialize body↵ at v (ht…polyfills.5d1d5b016f19755a7d41.bundle.js:1:35003)”}

    Please, I would appreciate your help. Thank you

  5. Thanks for your marvelous posting! I genuinely enjoyed reading it,
    you happen to be a great author.I will be sure
    to bookmark your blog and definitely will come back
    later in life. I want to encourage you to ultimately
    continue your great work, have a nice afternoon!

  6. I was wondering if you ever thought of changing the structure of
    your site? Its very well written; I love what youve got to
    say. But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

Leave a Reply

Your email address will not be published. Required fields are marked *