laravel 配置 elasticsearch

配置对应的版本  ~6.0  和你的安装的 elasticsearch 保持一致

composer require elasticsearch/elasticsearch:~6.0

修elasticsearch 配置文件 /etc/elasticsearch/elasticsearch.yml  (我安装的位置)

network.host: 192.168.0.1  -》network.host: 0.0.0.0  保持 为了让任何ip 访问

重启elasticsearch

service elasticsearch restart  

 

 

 

 

 

 

启动kibana  

/usr/share/kibana/bin/kibana

 

 

 

web.php

//elasticsearch 初始化操作
Route::get('/init',function(){
$hosts = [
'192.168.186.137:9200', // IP + Port 换成自己ip
];
$client = \Elasticsearch\ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
$params = [
'index' => 'product',
'body' => [
'settings' => [
'number_of_shards' => 1,
'number_of_replicas' => 0
],
'mappings' => [
'my_type' => [
'_source' => [
'enabled' => true
],
'properties' => [
'first_name' => [
'type' => 'keyword',
'analyzer' => 'standard'
],
'age' => [
'type' => 'integer'
]
]
]
]
]
];


// Create the index with mappings and settings now
$response = $client->indices()->create($params);

});


程序执行添加修改操作

$hosts = [
'192.168.186.137:9200', // IP + Port 换成自己的ip
];
$client = \Elasticsearch\ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
//写入文档
$params = [
'index' => 'product',
'type' => '_doc',
'id' => $product->id,
'body' => [
'title' => $product->title,
'description' => $product->description,
]
];

// Document will be indexed to my_index/my_type/my_id
$response = $client->index($params);


商品搜索
public function index(Request $request)
{
$where = [];
if($request->title)
{
//$where[] = ['title','like','%'.$request->title.'%'];
$where["title"] = [
"query"=>$request->title,
"slop"=>20
];
}
if($request->description)
{
//$where[] = ['description','like','%'.$request->description.'%'];
$where["description"] = [
"query"=>$request->description,
"slop"=>20
];
}

if($where)
{
$params = [
'index' => 'product',
'type' => '_doc',
'body' => [
'query' => [
'match_phrase' => $where
]
]
];
$hosts = [
'192.168.186.137:9200', // IP + Port
];
$client = \Elasticsearch\ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
$results = $client->search($params);

$products = $results['hits']['hits'];
}else{
$products = [];
}
// dump($results);exit;
// $products = Product::where($where)->get();

return view('product.index',compact('products'));
}




 

posted @ 2020-07-12 17:39  hubb  阅读(1777)  评论(0编辑  收藏  举报