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
Contents
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<CreateDocumentResponse>; |
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:
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
<div class="row"> <h3 class="col-md-8 text-center">Elasticsearch server status: {{status}}</h3> </div> <div class="col-md-8"> <div class="row"> <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)"> <div class="form-group"> <label class="control-label" for="index">Index</label> <input type="text" class="form-control" id="index" formControlName="index" [(ngModel)]="model.index" name="index"> </div> <div class="panel panel-primary"> <div class="panel-heading">Customer</div> <div class="panel-body"> <div class="form-group"> <label class="control-label" for="id">ID</label> <input type="number" class="form-control" id="id" formControlName="id" [(ngModel)]="model.id" name="id"> </div> <div class="form-group"> <label class="control-label" for="fullname">Full Name</label> <input type="text" class="form-control" id="fullname" formControlName="fullname" [(ngModel)]="model.fullname" name="fullname"> </div> <div class="form-group"> <label class="control-label" for="age">Age</label> <input type="number" class="form-control" id="age" formControlName="age" [(ngModel)]="model.age" name="age"> </div> <div class="form-group"> <label class="control-label" for="address">Address</label> <textarea class="form-control" id="address" formControlName="address" [(ngModel)]="model.address" name="address"> </textarea> </div> </div> </div> <button type="submit" [disabled]="!isConnected" class="btn btn-primary pull-right">Submit</button> </form> </div> </div> |
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
<div class="container" style="width: 600px"> <div style="color: blue; margin-bottom: 20px"> <h2>{{title}}</h2> <h4>{{description}}</h4> </div> <add-customer></add-customer> </div> |
5. Check Result
Run Angular 4 App, go to http://localhost:4200/
:
Submit Document and open Browser Console, you can see:
III. Sourcecode
Angular4ElasticSearch-addDocument
Last updated on August 14, 2018.