<?php
namespace App\Console\Commands;
use App\Models\Violation;
use App\Observers\ViolationObserver;
use Illuminate\Console\Command;
class CreateAndSyncElasticsearchIndexForViolation extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:create-and-sync-elasticsearch-index-for-violation';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle()
{
$indexName = ViolationObserver::VIOLATION_INDEX_NAME;
$client = app('elasticsearch');
try {
// $this->createIndex($client, $indexName);
// $this->syncData($client, $indexName);
$this->searchData($client, $indexName);
} catch (\Exception $e) {
dump("Error: " . $e->getMessage());
}
$this->info('Index created and data synchronized successfully');
}
/*
* searchData
*/
protected function searchData($client, $indexName)
{
// Violation::create([
// 'control_plate' => '21'
// ]);
// Violation::destroy(9);
$params = [
'index' => $indexName, // Replace with your index name
'body' => [
'query' => [
// 'match_all' => new \stdClass() // Match all documents
// 'match' => [
// 'control_plate' => '11111111' // Replace with your field and search value
// ],
'wildcard' => [
'control_plate' => '*2*'
]
]
]
];
try {
$response = $client->search($params);
if (isset($response['hits']['hits'])) {
foreach ($response['hits']['hits'] as $hit) {
echo 'ID: ' . $hit['_id'] . '<br>';
echo 'Source: ' . print_r($hit['_source'], true) . '<br><br>';
}
} else {
echo 'No results found';
}
} catch (\Exception $e) {
echo 'Error: ', $e->getMessage();
}
}
/*
* createIndex
*/
protected function createIndex($client, $indexName)
{
$params = [
'index' => $indexName,
'body' => [
'mappings' => [
'properties' => [
'id' => [
'type' => 'integer'
],
'control_plate' => [
'type' => 'text'
],
'status' => [
'type' => 'keyword'
]
]
]
]
];
try {
$response = $client->indices()->create($params);
$this->info('Index created: ' . $indexName);
} catch (\Exception $e) {
$this->error('Error creating index: ' . $e->getMessage());
}
}
/*
* syncData
*/
protected function syncData($client, $indexName)
{
$models = Violation::all(); // Fetch all records from the table
$params = ['body' => []];
foreach ($models as $model) {
// Add index operation for each record
$params['body'][] = [
'index' => [
'_index' => $indexName,
'_id' => $model->id,
]
];
$params['body'][] = [
'id' => $model->id,
'control_plate' => $model->control_plate,
'status' => $model->status,
];
}
try {
// Bulk index the records
$response = $client->bulk($params);
$this->info('Data synchronized successfully');
} catch (\Exception $e) {
$this->error('Error synchronizing data: ' . $e->getMessage());
}
}
}