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 } } } |
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<any> |
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:
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 grokonez!' }); } 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
<div class="row"> <h3>Elasticsearch server status: {{status}}</h3> </div> <div class="row"> <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)"> <label class="control-label" for="index">Index</label> <input type="text" class="form-control" id="index" formControlName="index"> <br/> <div class="panel panel-primary"> <div class="panel-heading">Customer</div> <div class="panel-body"> <label class="control-label" for="id">ID</label> <input type="number" class="form-control" id="id" formControlName="id"> <br/> <label class="control-label" for="fullname">Full Name</label> <input type="text" class="form-control" id="fullname" formControlName="fullname"> <br/> <label class="control-label" for="age">Age</label> <input type="number" class="form-control" id="age" formControlName="age"> <br/> <label class="control-label" for="address">Address</label> <textarea class="form-control" id="address" formControlName="address"></textarea> </div> </div> <button type="submit" [disabled]="!isConnected" class="btn btn-primary pull-right">Submit</button> </form> </div> |
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 = 'grokonez'; 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-add-customer></app-add-customer> </div> |
5. Check Result
Run Angular 6 App, go to http://localhost:4200/
:
Submit Document and open Browser Console, you can see:
Sourcecode
Angular6Elasticsearch-add-Document
ERROR TypeError: this.es.isAvailable is not a function
( I received this error)