首页 > 解决方案 > 无法连接到主机,elasticsearch 关闭?Symfony 4 elastica/rulfin 客户端。码头工人

问题描述

2天前我开始研究elasticsearch。一切都可以在 elasticsearch 服务器上索引和发送文档。但我无法使用elastica/ruflin客户端查询它们。

我正在开发 Symfony 4,我想实现搜索栏来查找文章。

不明白出了什么问题,因为我创建了一个填充索引的命令并且它可以工作。我可以在 kibana 或 localhost:9200/{index}/_search 上进行查询。

我用 docker 运行这个,webserver 是 nginx 并使用 php-fpm-7.2,

当我尝试查询错误是:无法连接到主机,Elasticsearch 关闭?

这是代码:

码头工人-compose.yml:

webserver:
  image: nginx:alpine
  container_name: docker-symfony4-webserver
  working_dir: /application
  volumes:
      - .:/application
      - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
  ports:
   - "8000:80"

php-fpm:
  build: phpdocker/php-fpm
  container_name: docker-symfony4-php-fpm
  working_dir: /application
  volumes:
    - .:/application
    - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.2/fpm/conf.d/99-overrides.ini

elasticsearch:
        image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2
        environment:
           - cluster.name=demo
           - bootstrap.memory_lock=true
           - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
           - transport.host=127.0.0.1
        ulimits:
            memlock:
                soft: -1
                hard: -1
        ports:
            - 9200:9200

控制器:

/**
 * @Route("/_search", methods={"GET"}, name="blog_search")
 */
public function search(Request $request, Client $client): Response
{

    if (!$request->isXmlHttpRequest()) {

        return $this->render('blog/search.html.twig');
    }

    $query = $request->query->get('q', '');
    $limit = $request->query->get('l', 10);

    $match = new MultiMatch();
    $match->setQuery($query);
    $match->setFields(["title^4", "summary", "content", "author"]);

    $bool = new BoolQuery();
    $bool->addMust($match);

    $elasticaQuery = new Query($bool);
    $elasticaQuery->setSize($limit);


    $foundPosts = $client->getIndex('blog')->search($elasticaQuery);
    $results = [];
    foreach ($foundPosts as $post) {
        $results[] = $post->getSource();
    }

    return $this->json($results);
}

服务.yaml:

Elastica\Client:
      $config:
          host: localhost

先感谢您!!

标签: symfonydockerelasticsearch

解决方案


您需要将主机设置为 elasticsearch docker 容器。
这里localhost指的是php-fpm容器,因为您的代码在其中执行。

所以配置文件应该是:

Elastica\Client:
    $config:
        host: elasticsearch
        port: 9200

推荐阅读