Angular 4 ElasticSearch example – Add Document to Index

In the post, we had known how to create an Index. This tutorial shows you way to add Document to Index (with Form).

Related Post:
Angular 4 ElasticSearch – Quick Start – How to add Elasticsearch.js
Angular 4 ElasticSearch example – How to create an 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:
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 Index & Check Connection

Please visit Angular 4 ElasticSearch example – How to create an Index for details.

3. Add Document to Index
3.1 ElasticSearch Service
import { Client } from 'elasticsearch';

@Injectable()
export class ElasticsearchService {

  private client: Client;
  //...

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

We use ElasticSearch Client.create() function that return a Promise:

create(params: CreateDocumentParams): Promise;

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

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

II. Practice

Project Structure:
angular-4-elasticsearch-add-document-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 { ElasticsearchService } from './elasticsearch.service';
import { AddCustomerComponent } from './customer/add-customer/add-customer.component';

@NgModule({
  declarations: [
    AppComponent,
    AddCustomerComponent
  ],
  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!'
    });
  }

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

add-customer.component.ts

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

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

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

  isConnected = false;

  form: FormGroup;
  status: string;
  model: any = {
    index: '',
    id: '',
    fullname: '',
    age: 0,
    address: ''
  };

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

    this.form = fbuilder.group({
      index: [''],
      id: [''],
      fullname: [''],
      age: 0,
      address: ['']
    });
  }

  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
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-document-result

Submit Document and open Browser Console, you can see:
angular-4-elasticsearch-add-document-result-console

III. Sourcecode

Angular4ElasticSearch-addDocument



By grokonez | October 15, 2017.

Last updated on August 14, 2018.



Related Posts


Got Something To Say:

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

*