Angular 4 ElasticSearch example – Get All Documents in Index

In the post, we had known how to add Document to Index. This tutorial shows you way to get all Documents and show them.

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 – Add Document to Index

More Practice:
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. Get All Documents in Index
3.1 ElasticSearch Service
import { Client } from 'elasticsearch';

@Injectable()
export class ElasticsearchService {

  private client: Client;

  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": "14/10/2017, 20:49:33"
          }
        },
        {
          "_source": {
            "fullname": "Katherin Kohen",
            "age": 22,
            "address": "1964 Facilisis Avenue\nBell Gardens Texas 87065",
            "published": "14/10/2017, 20:49:09"
          }
        },
        ...
}
3.2 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:

II. Practice

0. Overview

Goal:
angular-4-elasticsearch-get-all-documents-overview

Project Structure:
angular-4-elasticsearch-get-all-documents-structure

1. App Module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { ElasticsearchService } from './elasticsearch.service';
import { AddCustomerComponent } from './customer/add-customer/add-customer.component';
import { ShowCustomersComponent } from './customer/show-customers/show-customers.component';
import { CustomerDetailsComponent } from './customer/customer-details/customer-details.component';

@NgModule({
  declarations: [
    AppComponent,
    AddCustomerComponent,
    ShowCustomersComponent,
    CustomerDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule
  ],
  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;

  queryalldocs = {
    'query': {
      'match_all': {}
    }
  };

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

  getAllDocuments(_index, _type): any {
    return this.client.search({
      index: _index,
      type: _type,
      body: this.queryalldocs,
      filterPath: ['hits.hits._source']
    });
  }
}
3. Components
3.1 Add Document Component

Please visit: 3_Add_Document_Component (in the previous post) for details.

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

{{customer.fullname}}
{{customer.age}}
{{customer.address}}
{{customer.published}}

3.3 Show Documents Component

customer.interface.ts

export interface Customer {
    fullname: string;
    age: number;
    address: string;
    published: string;
}

export interface CustomerSource {
    source: Customer;
}

show-customers.component.ts

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

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 = 'jsa_customer_idx';
  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

4. App Routing Module
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 { }
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 = 'JavaSampleApproach';
  description = 'Angular4-SpringBoot Demo';
}

app.component.html

{{title}}

{{description}}

6. Check Result

Run Angular 4 App, go to http://localhost:4200/, add Customer Data, then choose Customers tab:
angular-4-elasticsearch-get-all-documents-overview

Open Browser Console, you can see:

TRACE: 2017-10-15T09:39:08Z
  -> POST http://localhost:9200/jsa_customer_idx/customer/_search?filter_path=hits.hits._source
  {
    "query": {
      "match_all": {}
    }
  }
  <- 200
  {
    "hits": {
      "hits": [
        {
          "_source": {
            "fullname": "David Louis",
            "age": 29,
            "address": "P.O. Box 399 4275 Amet Street\nWest Allis NC 36734",
            "published": "14/10/2017, 20:49:33"
          }
        },
        {
          "_source": {
            "fullname": "Jamie Konan",
            "age": 33,
            "address": "Ap #443-336 Ullamcorper. Street\nVisalia VA 54886",
            "published": "14/10/2017, 20:47:58"
          }
        },
        {
          "_source": {
            "fullname": "Katherin Kohen",
            "age": 22,
            "address": "1964 Facilisis Avenue\nBell Gardens Texas 87065",
            "published": "14/10/2017, 20:49:09"
          }
        },
		...
      ]
    }
  }		

III. Sourcecode

Angular4ElasticSearch-getDocuments



By grokonez | October 15, 2017.

Last updated on August 14, 2018.



Related Posts


2 thoughts on “Angular 4 ElasticSearch example – Get All Documents in Index”

  1. Hi there, great set of articles, would be great to have the full source code in a repo somewhere so that you can browse in your own time and use as a comparison. Had a look on gitlab but the repo seems empty 🙁 Still great set of articles but if you find time can you pop a link to a repo sometime. Thanks

    1. Hi opentuned,

      Thank you for your suggestion. We have plan for repo and will implement it in the future.

      Best Regard,
      JSA.

Got Something To Say:

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

*