本文的示例代码参考mysql-to-es
目录
Service
MySQL
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7.17
docker exec -i mysql mysql -uroot -p123456 <<< "CREATE DATABASE IF NOT EXISTS test DEFAULT CHARSET utf8 COLLATE utf8_general_ci;"
ElasticSearch
docker network create elastic
docker run --network=elastic --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -d elasticsearch:5.6.14
docker run --network=elastic --name kibana -p 5601:5601 -d kibana:5.6.14
docker run --name elasticsearch-kibana -p 9200:9200 -p 9300:9300 -p 5601:5601 -d nshou/elasticsearch-kibana
Laravel
MySQL
composer create-project laravel/laravel mysql-to-es --prefer-dist "5.5.*"
cd mysql-to-es
vim .env
# DB_DATABASE=test
# DB_USERNAME=root
# DB_PASSWORD=123456
php artisan make:seed UsersTableSeeder
vim database/seeds/UsersTableSeeder.php
<?php
use App\User;
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
public function run()
{
$users = factory(User::class)
->times(10)
->make();
$user_array = $users->makeVisible(['password', 'remember_token'])->toArray();
User::insert($user_array);
}
}
vim database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UsersTableSeeder::class);
}
}
php artisan migrate --seed
Scout
composer require laravel/scout ^5.0
composer require tamayo/laravel-scout-elastic
vim app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Scout\Searchable;
class User extends Authenticatable
{
use Notifiable;
use Searchable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
vim config/app.php
'providers' => [
Laravel\Scout\ScoutServiceProvider::class,
ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
],
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
vim config/scout.php
'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
...
'elasticsearch' => [
'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
'hosts' => [
env('ELASTICSEARCH_HOST', 'http://localhost:9200'),
],
],
php artisan scout:import "App\User"
# Imported [App\User] models up to ID: 10
# All [App\User] records have been imported.
Test
vim routes/web.php
<?php
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::get('/search', function (Request $request) {
return App\User::search($request->query('name'))->get();
});
php artisan serve
curl localhost:8000/search?name=ka | json
[
{
"id": 5,
"name": "Chanel Schiller DVM",
"email": "kade.grimes@example.net",
"created_at": null,
"updated_at": null
},
{
"id": 6,
"name": "Kamille Braun V",
"email": "lorenza.renner@example.net",
"created_at": null,
"updated_at": null
}
]
网友评论