We had known way to add Document to Elasticsearch Index, this tutorial shows you how to get all Documents and show them.
Related Posts:
– Angular 6 ElasticSearch – Quick Start – How to add Elasticsearch.js
– Angular 6 ElasticSearch example – Add Document to Index
– Next:
+ Angular 6 ElasticSearch example – Documents Pagination with Scroll
+ Angular 6 ElasticSearch example – simple Full Text Search
Get all Documents in 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
Add Document to Index
Please visit Angular 6 ElasticSearch example – Add Document to Index for details.
Get All Documents in Index
ElasticSearch Service
import { Client } from 'elasticsearch-browser'; @Injectable() export class ElasticsearchService { private client: Client; private queryalldocs = { 'query': { 'match_all': {} } }; getAllDocuments(_index, _type): any { return this.client.search({ index: _index, type: _type, body: this.queryalldocs, filterPath: ['hits.hits._source'] }); } } |
The response of search()
function should be like:
{ "hits": { "hits": [ { "_source": { "fullname": "David Louis", "age": 29, "address": "P.O. Box 399 4275 Amet Street\nWest Allis NC 36734", "published": "15/08/2018, 10:32:23" } }, { "_source": { "fullname": "Katherin Kohen", "age": 22, "address": "1964 Facilisis Avenue\nBell Gardens Texas 87065", "published": "15/08/2018, 10:33:09" } }, ... } |
Component to implement
customerSources: CustomerSource[]; constructor(private es: ElasticsearchService); // ... this.es.getAllDocuments('index', 'type') .then(response => { this.customerSources = response.hits.hits; console.log(response); }, error => { console.error(error); }).then(() => { console.log('Show Customer Completed!'); }); |
With CustomerSource
interface:
export interface CustomerSource { source: Customer; } |
In HTML, we get Customer
from CustomerSource._source
:
<div *ngFor="let customerSource of customerSources"> <customer-details [customer]='customerSource._source'></customer-details> </div> |
Practice
0. Overview
Goal:
1. Generate Service & Components
Run cmd:
– ng g s elasticsearch
– ng g c customer/add-customer
– ng g c customer/customer-details
– ng g c customer/show-customers
=> 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 { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AddCustomerComponent } from './customer/add-customer/add-customer.component'; import { CustomerDetailsComponent } from './customer/customer-details/customer-details.component'; import { ShowCustomersComponent } from './customer/show-customers/show-customers.component'; @NgModule({ declarations: [ AppComponent, AddCustomerComponent, CustomerDetailsComponent, ShowCustomersComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, AppRoutingModule ], 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; private queryalldocs = { 'query': { 'match_all': {} } }; 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); } getAllDocuments(_index, _type): any { return this.client.search({ index: _index, type: _type, body: this.queryalldocs, filterPath: ['hits.hits._source'] }); } } |
4. Components
customer/customer.interface.ts
export interface Customer { fullname: string; age: number; address: string; published: string; } export interface CustomerSource { source: Customer; } |
4.1 Add Document Component
Please visit: 4_Add_Document_Component (in the previous post) for details.
4.2 Details Component
customer-details.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { Customer } from '../customer.interface'; @Component({ selector: 'customer-details', templateUrl: './customer-details.component.html', styleUrls: ['./customer-details.component.css'] }) export class CustomerDetailsComponent implements OnInit { @Input() customer: Customer; constructor() { } ngOnInit() { } } |
customer-details.component.html
<div *ngIf="customer"> <div> <label>Full Name: </label> {{customer.fullname}} </div> <div> <label>Age: </label> {{customer.age}} </div> <div> <label>Address: </label> {{customer.address}} </div> <div> <label>Published: </label> {{customer.published}} </div> <hr/> </div> |
4.3 Show Documents Component
show-customers.component.ts
import { Component, OnInit } from '@angular/core'; import { CustomerSource } from '../customer.interface'; import { ElasticsearchService } from '../../elasticsearch.service'; @Component({ selector: 'show-customers', templateUrl: './show-customers.component.html', styleUrls: ['./show-customers.component.css'] }) export class ShowCustomersComponent implements OnInit { private static readonly INDEX = 'gkz_index'; private static readonly TYPE = 'customer'; customerSources: CustomerSource[]; constructor(private es: ElasticsearchService) { } ngOnInit() { this.es.getAllDocuments(ShowCustomersComponent.INDEX, ShowCustomersComponent.TYPE) .then(response => { this.customerSources = response.hits.hits; console.log(response); }, error => { console.error(error); }).then(() => { console.log('Show Customer Completed!'); }); } } |
show-customers.component.html
<div *ngFor="let customerSource of customerSources" style="margin-top:20px"> <customer-details [customer]='customerSource._source'></customer-details> </div> |
5. App Routing Module
app-routing.module.ts
import { AddCustomerComponent } from './customer/add-customer/add-customer.component'; import { ShowCustomersComponent } from './customer/show-customers/show-customers.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: '', redirectTo: 'add', pathMatch: 'full' }, { path: 'add', component: AddCustomerComponent }, { path: 'customers', component: ShowCustomersComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } |
6. 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"> <h2>{{title}}</h2> <h4>{{description}}</h4> </div> <nav> <a routerLink="add" class="btn btn-primary active" role="button" routerLinkActive="active">Add</a> <a routerLink="customers" class="btn btn-primary active" role="button" routerLinkActive="active">Customers</a> </nav> <router-outlet></router-outlet> </div> |
7. Check Result
Run Angular 6 App, go to http://localhost:4200/
, add Customer Data, then choose Customers tab:
Open Browser Console, you can see:
TRACE: 2018-08-15T13:15:42Z -> POST http://localhost:9200/gkz_index/customer/_search?filter_path=hits.hits._source { "query": { "match_all": {} } } <- 200 { "hits": { "hits": [ { "_source": { "fullname": "Jamie Konan", "age": 33, "address": "Ap #443-336 Ullamcorper. Street\nVisalia VA 54886", "published": "15/08/2018, 10:32:47" } }, { "_source": { "fullname": "David Louis", "age": 29, "address": "P.O. Box 399 4275 Amet Street\nWest Allis NC 36734", "published": "15/08/2018, 10:32:23" } }, { "_source": { "fullname": "Katherin Kohen", "age": 22, "address": "1964 Facilisis Avenue\nBell Gardens Texas 87065", "published": "15/08/2018, 10:33:09" } } ] } } |
Your code is very helpful. I appreciate it so much. I was wondering if you would know how to search using “elasticsearch-browser”: “^16.2.0” for a specific field in an index and get back only non duplicates of that field?
I am currently getting documents back from elasticsearch and then I loop on the documents, creating a Set of a particular field (deduping) from that response, however I have it set to retrieve 150 documents, but when I get the zip code field for example, there are tons of duplicates and then since I only got 150 responses, when I dedupe those, I am left with very few fields to display to the user. I would like to display (with a scroll bar), all of the zip codes (up to a count of 150).
Thank you so much!!!
Don