弹性搜索失败,无法连接到主机? Symfony 4 Elastica / Rulfin客户。码头工人

时间:2018-10-12 13:00:33

标签: symfony docker elasticsearch

2天前,我开始从事Elasticsearch。可以在Elasticsearch服务器上建立索引并发送文档。但是我无法使用 elastica / ruflin 客户端查询它们。

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

不知道这是怎么回事,因为我创建了一个填充索引的命令并且它可以工作。我可以在kibana或localhost:9200 / {index} / _ search上查询。

我正在用docker运行它,网络服务器是nginx并使用php-fpm-7.2,

当我尝试进行查询错误时:无法连接至主机,Elasticsearch断开?

代码如下:

docker-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);
}

services.yaml:

Elastica\Client:
      $config:
          host: localhost

提前谢谢!

2 个答案:

答案 0 :(得分:1)

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

因此配置文件应为:

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

答案 1 :(得分:0)

您解决了问题吗?

您忘记添加这样的容器名称 container_name:elasticsearch 要恢复,您将拥有:

 elasticsearch:
        image: docker.elastic.co/elasticsearch/elasticsearch:6.4.2
        container_name: elasticsearch
        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