laravel 配置 elasticsearch

Posted hubb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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\'));
}




 

以上是关于laravel 配置 elasticsearch的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 基于 Scout 配置实现 Elasticsearch

laravel-elasticsearch 全文搜索设置

Laravel快速使用Elasticsearch

用elasticsearch-php laravel为啥不能返回高亮数据

laravel 5.5 elasticsearch/elasticsearch 插件安装及使用

搜索引擎之laravel中使用elasticsearch