Angular 6 ElasticSearch example – Add Document to Index

In this Angular Elasticsearch tutorial, we’re gonna add Document to Index (with Form).

Related Posts:
Angular 6 ElasticSearch – Quick Start – How to add Elasticsearch.js
– Next: Angular 6 ElasticSearch example – Get All Documents in Index

Way to add Document to Elasticsearch Index

Add ElasticSearch to Angular 6 Project

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

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

Create Index & Check Connection

Use Kibana for creating Elasticsearch Index (gkz_index):

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

angular-6-elasticsearch-example-add-document-to-index-create-index

Add Document to Index
ElasticSearch Service
import { Client } from 'elasticsearch-browser';

@Injectable()
export class ElasticsearchService {

  private client: Client;
  //...

  addToIndex(value): any {
    return this.client.create(value);
  }
}

We use ElasticSearch Client.create() function that return an Observable:

create(params: CreateDocumentParams): Observable

The params should have at least index, type, id to make it work.

Component to implement
constructor(private es: ElasticsearchService);

this.es.addToIndex({
  index: 'index',
  type: 'customer',
  id: id,
  body: {
    fullname: 'fullname',
    age: age,
    address: 'address',
    published: new Date().toLocaleString()
  }
}).then((result) => {
  console.log(result);
  alert('Document added, see log for more info');
}, error => {
  alert('Something went wrong, see log for more info');
  console.error(error);
});

Practice

1. Generate Service & Component

Run cmd:
ng g s elasticsearch
ng g c customer/add-customer

=> Project Structure:

angular-6-elasticsearch-example-add-document-to-index-project-structure

2. App Module

app.module.ts

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

import { AppComponent } from './app.component';
import { AddCustomerComponent } from './customer/add-customer/add-customer.component';

@NgModule({
  declarations: [
    AppComponent,
    AddCustomerComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
3. ElasticSearch Service

elasticsearch.service.ts

import { Injectable } from '@angular/core';
import { Client } 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'
    });
  }

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

  addToIndex(value): any {
    return this.client.create(value);
  }
}
4. Add Document Component

add-customer.component.ts

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { ElasticsearchService } from '../../elasticsearch.service';

@Component({
  selector: 'app-add-customer',
  templateUrl: './add-customer.component.html',
  styleUrls: ['./add-customer.component.css']
})
export class AddCustomerComponent implements OnInit {

  isConnected = false;

  form: FormGroup;
  status: string;

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

    this.form = new FormGroup({
      index: new FormControl('gkz_index', Validators.required),
      id: new FormControl('', Validators.required),
      fullname: new FormControl('', Validators.required),
      age: new FormControl('', Validators.required),
      address: new FormControl('', Validators.required),
    });
  }

  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.addToIndex({
      index: value.index,
      type: 'customer',
      id: value.id,
      body: {
        fullname: value.fullname,
        age: value.age,
        address: value.address,
        published: new Date().toLocaleString()
      }
    }).then((result) => {
      console.log(result);
      alert('Document added, see log for more info');
    }, error => {
      alert('Something went wrong, see log for more info');
      console.error(error);
    });
  }
}

add-customer.component.html

Elasticsearch server status: {{status}}


Customer



5. 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

{{title}}

{{description}}

5. Check Result

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

angular-6-elasticsearch-example-add-document-to-index-add-document
Submit Document and open Browser Console, you can see:

angular-6-elasticsearch-example-add-document-to-index-console-result

Sourcecode

Angular6Elasticsearch-add-Document

3 thoughts on “Angular 6 ElasticSearch example – Add Document to Index”

  1. Wonderful website you have here but I was wanting to know if you knew of any community forums that cover the same topics discussed in this article? I’d really love to be a part of community where I can get suggestions from other knowledgeable individuals that share the same interest. If you have any recommendations, please let me know. Cheers!

Leave a Reply

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