下载symfony
略
创建一个symfony 3 项目
代码语言:javascript复制cd /var/www
symfony new search-www
修改composer.json,增加
代码语言:javascript复制"require": {
...
"elasticsearch/elasticsearch": "~5.3.0"
...
}
如果composer.json.lock存在,则删除。
安装elasticsearch 库
代码语言:javascript复制cd /var/www/search-www
composer install
Symfony项目中创建一个Controller
目录src/AppBundle/Controller/SearchController.php
代码语言:javascript复制<?php
namespace AppBundleController;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use ElasticsearchClientBuilder;
class SearchController extends Controller
{
/**
* @Route("/search", name="homepage")
*/
public function indexAction(Request $request)
{
$client = ClientBuilder::create()->build();
$params = [
'index' => 'scrapy.course',
'type' => 'normal',
'id' => '1'
];
$response = $client->get($params);
return new Response(json_encode($response));
}
}
启动symfony服务
代码语言:javascript复制app/console server:run
默认端口为8000
查询结果
http://localhost:8000/search
代码语言:javascript复制{
"_index":"scrapy.course",
"_type":"normal",
"_id":"1",
"_version":1,
"found":true,
"_source":{
"title":"Think in Java"
}
}
注: 需要先搭建elasticsearch并插入数据,参见文档undefined 《Elasticsearch Kibana 起步》
参考文档 https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_quickstart.html