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

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

Related Posts:
Angular 8 ElasticSearch example – Add Document to Index
Angular 8 ElasticSearch example – Get All Documents in Index
Angular 8 ElasticSearch example – Documents Pagination with Scroll
Angular 8 ElasticSearch example – simple Full Text Search

** Elasticsearch Tutorials **

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":"6.3.2",
      "build_flavor":"unknown",
      "build_type":"unknown",
      "build_hash":"053779d",
      "build_date":"2018-07-20T05:20:23.451332Z",
      "build_snapshot":false,
      "lucene_version":"7.3.1",
      "minimum_wire_compatibility_version":"5.6.0",
      "minimum_index_compatibility_version":"5.0.0"
   },
   "tagline":"You Know, for Search"
}

Add ElasticSearch to Angular 8 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-6-elasticsearch-example-quick-start-node-modules

2. Add dependency

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


...
"dependencies": {
	"elasticsearch-browser": "^15.1.1",
	...
},
...

Re-install your Angular 8 Project:
npm install

Use ElasticSearch in Angular 8 Project

1. Import and use


import * as elasticsearch from 'elasticsearch-browser';

//...

  private client: elasticsearch.Client

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

or:


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

  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: 2018-08-13T07:34:46Z
  -> HEAD http://localhost:9200/
  hello ozenero!
  <- 200

Practice

1. Generate Service & Component

Run cmd:
- ng g s elasticsearch
- ng g c test-es

=> Project Structure:

angular-6-elasticsearch-example-quick-start-structure

=> App Module:
app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestEsComponent } from './test-es/test-es.component';

@NgModule({
  declarations: [
    AppComponent,
    TestEsComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. ElasticSearch Service

elasticsearch.service.ts


import { Injectable } from '@angular/core';
import { Client } from 'elasticsearch-browser';
import * as elasticsearch from 'elasticsearch-browser';

@Injectable({
  providedIn: 'root'
})
export class ElasticsearchService {

  private client: Client;

  constructor() {
    if (!this.client) {
      this._connect();
    }
  }

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

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

  isAvailable(): any {
    return this.client.ping({
      requestTimeout: Infinity,
      body: 'hello ozenero!'
    });
  }
}

2. Test Component

test-es.component.ts


import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ElasticsearchService } from '../elasticsearch.service';

@Component({
  selector: 'app-test-es',
  templateUrl: './test-es.component.html',
  styleUrls: ['./test-es.component.css']
})
export class TestEsComponent implements OnInit {
  isConnected = false;
  status: string;

  constructor(private es: ElasticsearchService, private cd: ChangeDetectorRef) {
    this.isConnected = false;
  }

  ngOnInit() {
    this.es.isAvailable().then(() => {
      this.status = 'OK';
      this.isConnected = true;
    }, error => {
      this.status = 'ERROR';
      this.isConnected = false;
      console.error('Server is down', error);
    }).then(() => {
      this.cd.detectChanges();
    });
  }

}

test-es.component.html

<h3 class="col-md-12 text-center">Elasticsearch server status: {{status}}</h3>

4. App Component

app.component.ts


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ozenero';
  description = 'Angular - Elasticsearch';
}

app.component.html

<div class="container" style="width: 400px">
	<div style="color: blue; margin-bottom: 20px">
		<h1>{{title}}</h1>
		<h3>{{description}}</h3>
	</div>
 
	<app-test-es></app-test-es>
</div>

5. Check Result

Run Angular 8 App, go to http://localhost:4200/:

angular-6-elasticsearch-example-quick-start-result

Open Browser Console, we can see:

angular-6-elasticsearch-example-quick-start-result-console

Source Code

Angular6Elasticsearch

128 thoughts on “Angular 8 ElasticSearch – Quick Start – How to add Elasticsearch.js”

  1. Elasticsearch guide more tutorial man – I need it for project ! I contact with you oki?

  2. Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to everything. Do you have any suggestions for first-time blog writers? I’d certainly appreciate it.

  3. certainly like your web site however you have to check the spelling on several of your posts. Many of them are rife with spelling issues and I find it very troublesome to tell the truth then again I will certainly come again again.

  4. An attention-grabbing dialogue is price comment. I believe that it is best to write more on this matter, it might not be a taboo topic but usually people are not sufficient to talk on such topics. To the next. Cheers

  5. I used to be suggested this website via my cousin. I’m not positive whether this post is written by means of him as nobody else understand such certain about my difficulty. You are incredible! Thanks!

  6. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  7. Throughout this grand pattern of things you’ll receive a B+ with regard to hard work. Exactly where you actually lost me ended up being on your specifics. You know, they say, the devil is in the details… And that could not be much more true right here. Having said that, allow me reveal to you what exactly did give good results. Your authoring can be highly engaging which is possibly the reason why I am taking an effort in order to comment. I do not make it a regular habit of doing that. Next, while I can easily notice a leaps in reason you come up with, I am definitely not convinced of how you appear to unite the ideas which in turn help to make the final result. For the moment I will yield to your issue however hope in the near future you connect the facts better.

  8. This is the proper blog for anybody who wants to find out about this topic. You realize a lot its virtually onerous to argue with you (not that I actually would need…HaHa). You definitely put a new spin on a subject thats been written about for years. Nice stuff, simply nice!

  9. I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  10. I do agree with all of the ideas you’ve presented in your post. They are really convincing and will definitely work. Still, the posts are too short for newbies. Could you please extend them a little from next time? Thanks for the post.

  11. I precisely had to thank you so much once again. I’m not certain the things I would’ve used without those basics documented by you relating to my subject. It had been a real distressing concern in my opinion, nevertheless finding out your specialized way you handled the issue forced me to weep over joy. I will be happier for this help and hope you really know what a powerful job you happen to be providing instructing the mediocre ones using a blog. I am certain you’ve never got to know all of us.

  12. Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch since I found it for him smile Therefore let me rephrase that: Thank you for lunch! “Do you want my one-word secret of happiness–it’s growth–mental, financial, you name it.” by Harold S. Geneen.

  13. There are certainly a whole lot of details like that to take into consideration. That could be a great point to deliver up. I provide the ideas above as normal inspiration however clearly there are questions like the one you carry up the place crucial factor shall be working in honest good faith. I don?t know if finest practices have emerged around issues like that, however I’m certain that your job is clearly recognized as a good game. Each boys and girls feel the impact of just a second’s pleasure, for the rest of their lives.

  14. I like what you guys are up too. Such clever work and reporting! Carry on the superb works guys I?¦ve incorporated you guys to my blogroll. I think it’ll improve the value of my website 🙂

  15. Hello there, just became aware of your blog through Google, and found that it is really informative. I am going to watch out for brussels. I’ll appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!

  16. Whats Going down i am new to this, I stumbled upon this I’ve found It absolutely useful and it has helped me out loads. I’m hoping to give a contribution & help other customers like its aided me. Great job.

  17. I beloved as much as you’ll receive performed right here. The cartoon is attractive, your authored subject matter stylish. nevertheless, you command get bought an impatience over that you want be delivering the following. unwell without a doubt come further beforehand again as precisely the same just about very ceaselessly inside case you defend this increase.

  18. Hello There. I discovered your blog using msn. This is a really well written article. I will be sure to bookmark it and come back to learn extra of your useful information. Thank you for the post. I will definitely comeback.

  19. I am not sure where you are getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  20. My spouse and I absolutely love your blog and find almost all of your post’s to be just what I’m looking for. Would you offer guest writers to write content for you? I wouldn’t mind composing a post or elaborating on a number of the subjects you write concerning here. Again, awesome web log!

  21. Thank you for your entire effort on this web site. Kim really loves conducting investigations and it is simple to grasp why. We notice all about the lively mode you make valuable tips and hints by means of your web site and even cause response from other people on that topic and our favorite daughter is really discovering so much. Take advantage of the remaining portion of the new year. You’re doing a superb job.

  22. I have been exploring for a little for any high-quality articles or blog posts in this kind of space . Exploring in Yahoo I finally stumbled upon this web site. Studying this information So i am satisfied to convey that I’ve an incredibly just right uncanny feeling I found out just what I needed. I such a lot indisputably will make certain to don?¦t overlook this web site and give it a glance on a continuing basis.

  23. With every little thing that seems to be developing inside this particular subject matter, all your viewpoints are generally quite stimulating. Even so, I appologize, but I can not subscribe to your whole suggestion, all be it refreshing none the less. It seems to us that your remarks are not totally justified and in actuality you are generally yourself not really wholly certain of your point. In any event I did take pleasure in examining it.

  24. I have fun with, cause I discovered just what I used to be having a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  25. This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

  26. I got what you intend, regards for putting up.Woh I am pleased to find this website through google. “I would rather be a coward than brave because people hurt you when you are brave.” by E. M. Forster.

  27. Only wanna comment on few general things, The website design is perfect, the written content is real superb. “Drop the question what tomorrow may bring, and count as profit every day that fate allows you.” by Horace.

  28. We’re a group of volunteers and starting a brand new scheme in our community. Your web site offered us with helpful information to paintings on. You have performed a formidable activity and our entire community will likely be thankful to you.

  29. I am really enjoying the theme/design of your website. Do you ever run into any web browser compatibility issues? A handful of my blog audience have complained about my blog not working correctly in Explorer but looks great in Safari. Do you have any solutions to help fix this issue?

  30. Hi, Neat post. There is an issue along with your web site in internet explorer, could check this?K IE still is the marketplace leader and a large element of other folks will pass over your fantastic writing due to this problem.

  31. Hi, Neat post. There’s a problem along with your site in internet explorer, could test this?K IE still is the marketplace leader and a good component of folks will pass over your excellent writing because of this problem.

  32. Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  33. Hey very nice website!! Man .. Excellent .. Amazing .. I’ll bookmark your website and take the feeds also…I am happy to find numerous useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  34. You could certainly see your expertise within the work you write. The arena hopes for even more passionate writers like you who are not afraid to mention how they believe. At all times go after your heart.

  35. Thanks for sharing excellent informations. Your site is so cool. I’m impressed by the details that you have on this blog. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the information I already searched everywhere and just could not come across. What a great web site.

  36. magnificent issues altogether, you simply gained a new reader. What might you recommend in regards to your submit that you just made a few days in the past? Any positive?

  37. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade site post from you in the upcoming as well. Actually your creative writing abilities has inspired me to get my own site now. Actually the blogging is spreading its wings fast. Your write up is a great example of it.

  38. I?¦m not certain where you are getting your information, but great topic. I needs to spend some time studying more or figuring out more. Thank you for magnificent info I was in search of this info for my mission.

  39. Does your website have a contact page? I’m having a tough time locating it but, I’d like to shoot you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it grow over time.

  40. I’m still learning from you, while I’m trying to achieve my goals. I certainly love reading all that is written on your website.Keep the posts coming. I liked it!

  41. Hi, Neat post. There’s an issue along with your web site in web explorer, might test this… IE nonetheless is the market leader and a big section of folks will leave out your great writing because of this problem.

  42. 344063 378495My brother suggested I would possibly like this weblog. He was once entirely appropriate. This submit truly created my day. You cant believe just how so a lot time I had spent for this info! Thank you! 955589

  43. I was recommended this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble. You are incredible! Thanks!

  44. Some really good info , Sword lily I observed this. “The minute one utters a certainty, the opposite comes to mind.” by May Sarton.

  45. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  46. I would like to thnkx for the efforts you’ve put in writing this site. I am hoping the same high-grade website post from you in the upcoming as well. Actually your creative writing abilities has encouraged me to get my own site now. Actually the blogging is spreading its wings quickly. Your write up is a good example of it.

  47. Hey there would you mind stating which blog platform you’re using? I’m planning to start my own blog in the near future but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

  48. I like the helpful info you provide for your articles. I’ll bookmark your blog and take a look at once more right here regularly. I’m fairly sure I will learn many new stuff right here! Best of luck for the next!

  49. My husband and i felt very joyous that Ervin managed to finish off his basic research via the ideas he made through your blog. It is now and again perplexing to just continually be releasing secrets and techniques which usually men and women may have been selling. We do understand we now have the website owner to appreciate because of that. The type of illustrations you have made, the simple blog menu, the friendships you give support to foster – it is everything superb, and it’s really helping our son in addition to us consider that that topic is interesting, and that is very indispensable. Many thanks for everything!

  50. Good ?V I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your customer to communicate. Nice task..

  51. What’s Taking place i’m new to this, I stumbled upon this I have discovered It absolutely helpful and it has helped me out loads. I hope to give a contribution & assist other customers like its helped me. Good job.

  52. Pretty nice post. I just stumbled upon your weblog and wished to say that I’ve truly enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again very soon!

  53. I have read some good stuff here. Definitely value bookmarking for revisiting. I surprise how so much attempt you place to make this kind of great informative website.

  54. What i do not realize is in truth how you are not actually much more neatly-preferred than you might be right now. You’re very intelligent. You recognize therefore considerably with regards to this topic, made me individually believe it from numerous various angles. Its like men and women aren’t interested until it is something to accomplish with Woman gaga! Your own stuffs outstanding. At all times care for it up!

  55. I have recently started a web site, the information you provide on this site has helped me greatly. Thank you for all of your time & work. “Never trust anybody who says ‘trust me.’ Except just this once, of course. – from Steel Beach” by John Varley.

  56. Normally I do not learn article on blogs, however I would like to say that this write-up very compelled me to try and do so! Your writing style has been surprised me. Thanks, very nice post.

  57. I’m not sure exactly why but this weblog is loading extremely slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later on and see if the problem still exists.

  58. Thank you for some other informative site. The place else could I get that kind of info written in such a perfect manner? I’ve a project that I am just now running on, and I’ve been at the look out for such info.

Leave a Reply

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