Symfony 3 框架+Elasticsearch

  • 2019 年 10 月 6 日
  • 筆記

下载symfony

创建一个symfony 3 项目

cd /var/www  symfony new search-www

修改composer.json,增加

"require": {  ...      "elasticsearch/elasticsearch": "~5.3.0"  ...  }

如果composer.json.lock存在,则删除。

安装elasticsearch 库

cd /var/www/search-www  composer install

Symfony项目中创建一个Controller

目录src/AppBundle/Controller/SearchController.php

<?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服务

app/console server:run

默认端口为8000

查询结果

http://localhost:8000/search

{      "_index":"scrapy.course",      "_type":"normal",      "_id":"1",      "_version":1,      "found":true,      "_source":{          "title":"Think in Java"      }  }

注: 需要先搭建elasticsearch并插入数据,参见文档 《Elasticsearch + Kibana 起步》

参考文档 https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_quickstart.html