DEV Community

Cover image for Query through Elasticsearch Indices with Laravel
Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on • Edited on

Query through Elasticsearch Indices with Laravel

Just come across a use case during my daily works, to query through Elasticearch indices, in Laravel.

I'm assuming you have installed Elasticsearch, have indices, index pattern defined and of course, data populated in the index documents.

Then, create a Laravel project and install this Laravel Elasticsearch package.

Then, let's create a file in your laravel project - I've create a directory called tinker/ and created tinker/es.php in it.

Then paste the following codes in the file.

<?php 

$stat = Elasticsearch::indices()->stats(['index'=>'your-index-*']);
$indices = $stat['indices'];
$field = 'username.keyword';
$keyword = 'xyz';
$list = [];
foreach ($indices as $key => $value) {
    echo $key . PHP_EOL;

    $data = [
        'index' => $key,
        'body'  => [
            'query' => [
                'match' => [
                    $field => $keyword,
                ]
            ]
        ]
    ];
    $list[] = Elasticsearch::search($data);
}
dd($list);
Enter fullscreen mode Exit fullscreen mode

Run the above command:

php artisan tinker tinker/es.php
Enter fullscreen mode Exit fullscreen mode

The above code should return something like:

your-index-2021.09.12
array:1 [
  0 => array:4 [
    "took" => 5
    "timed_out" => false
    "_shards" => array:4 [
      "total" => 1
      "successful" => 1
      "skipped" => 0
      "failed" => 0
    ]
    "hits" => array:3 [
      "total" => array:2 [
        "value" => 1
        "relation" => "eq"
      ]
      "max_score" => 0.2876821
      "hits" => array:1 [
        0 => array:5 [
          "_index" => "your-index-2021.09.12"
          "_type" => "_doc"
          "_id" => "xH652nsBOpLioOpWB7gH"
          "_score" => 0.2876821
          "_source" => array:7 [
            "password" => "xyz"
            "username" => "xyz"
            "@timestamp" => "2021-09-12T15:56:03.935Z"
            "port" => 50784
            "tags" => array:1 [
              0 => "your-index"
            ]
            "@version" => "1"
            "host" => "localhost"
          ]
        ]
      ]
    ]
  ]
]
Enter fullscreen mode Exit fullscreen mode

The cover image is an incoming event for JomLaunch 2021. You can buy tickets from https://launch.jomweb.my/. Every year, the JOMWEB Facebook Group community (facebook.com/groups/jomweb) which consists of programmers, developers, UI/UX designers, security experts, and other ICT activists in the country gather to highlight their projects. This is all to celebrate the country's ICT talents and expertise, and take the opportunity to get to know and learn from each other. This year 2021, JOMLAUNCH continues again, digitally.

Top comments (0)