Angular 4 ElasticSearch example – How to create an Index

In this tutorial, we’re gonna look at way to create an Elasticsearch Index in an Angular 4 Project.

Related Posts:
Angular 4 ElasticSearch – Quick Start – How to add Elasticsearch.js
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

Elasticsearch Tutorials:
Elasticsearch Overview
ElasticSearch Filter vs Query
ElasticSearch Full Text Queries – Basic

I. How to

1. Add ElasticSearch to Angular 4 Project

Please visit Angular 4 ElasticSearch – Quick Start – How to add Elasticsearch.js for details.

With the post, you will know how to:
– Install ElasticSearch
– Add ElasticSearch to Angular 4 Project
– Use it in the project

2. Create an ElasticSearch Index
2.1 Connect to ElasticSearch
import { Client } from 'elasticsearch';
// ...
private client: Client;

private connect() {
  this.client = new Client({
    host: 'http://localhost:9200',
    log: 'trace'
  });
}
2.2 Ping ElasticSearch
this.client.ping({
  requestTimeout: Infinity,
  body: 'hello JavaSampleApproach!'
});

If server is available, your Browser console shows:

TRACE: 2017-10-13T08:55:32Z
  -> HEAD http://localhost:9200/
  hello JavaSampleApproach!
  <- 200

Now you can create an Index.

2.3 Create an ElasticSearch Index
this.client.indices.create({ index: 'index_name' }).then(
      result => {
        console.log(result);
        alert('Index added, see log for more info');
      }, error => {
        alert('Something went wrong, see log for more info');
        console.error(error);
      }
    );

II. Practice

Project Structure:
angular-4-elasticsearch-add-index-structure

1. App Module
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

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

@NgModule({
  declarations: [
    AppComponent,
    TestEsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [ElasticsearchService],
  bootstrap: [AppComponent]
})

export class AppModule {}
2. ElasticSearch Service
import { Injectable } from '@angular/core';

import { Client } from 'elasticsearch';

@Injectable()
export class ElasticsearchService {

  private client: Client;

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

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

  createIndex(name): any {
    return this.client.indices.create(name);
  }

  isAvailable(): any {
    return this.client.ping({
      requestTimeout: Infinity,
      body: 'hello JavaSampleApproach!'
    });
  }
}
3. Add Test Component

test-es.component.ts

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

import { FormBuilder, FormGroup } from '@angular/forms';
import { ElasticsearchService } from '../elasticsearch.service';

@Component({
  selector: 'test-es',
  templateUrl: './test-es.component.html',
  styleUrls: ['./test-es.component.css']
})
export class TestEsComponent implements OnInit {

  isConnected = false;

  form: FormGroup;
  status: string;

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

    this.form = fbuilder.group({
      index: '',
    });
  }

  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();
    });
  }

  onSubmit(value) {

    this.es.createIndex({ index: value.index }).then(
      result => {
        console.log(result);
        alert('Index added, see log for more info');
      }, error => {
        alert('Something went wrong, see log for more info');
        console.error(error);
      }
    );
  }
}

test-es.component.html

Elasticsearch server status: {{status}}

Post index

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 = 'JavaSampleApproach';
  description = 'Angular4-SpringBoot Demo';
}

app.component.html

{{title}}

{{description}}

5. Check Result

Run Angular 4 App, go to http://localhost:4200/:
angular-4-elasticsearch-add-index-result-url

Open Browser Console, we can see:
angular-4-elasticsearch-add-index-result-console-ok

Fill index in the box (for example: jsa_index) and press Submit button, we can see:
- in Browser Console:
angular-4-elasticsearch-add-index-result-console-ack

- in ElasticSearch Console:
angular-4-elasticsearch-add-index-result-console-elasticsearch

III. Sourcecode

Angular4ElasticSearch-createIndex



By grokonez | October 13, 2017.

Last updated on August 14, 2018.



Related Posts


Got Something To Say:

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

*