ElasticSearch索引不适用于Symfony 4

时间:2019-03-18 10:40:14

标签: symfony elasticsearch symfony4

我正在尝试使用ElasticSearch为我的文章建立索引(当前使用symfony演示项目)。我正在使用"ruflin/elastica": "^6.1"捆绑包。

我在kibana上测试了索引,该索引正在运行,但是我的控制器似乎无法与ES正确通信:

BlogController.php:

use Elastica\Query;
use Elastica\Client;
use Elastica\Query\BoolQuery;
use Elastica\Query\MultiMatch;
/**
 * @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"]);

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

这是我用来为文章编制索引的类:

ArticleIndexer.php:

namespace App\Elasticsearch;

use App\Entity\Post;
use App\Repository\PostRepository;
use Elastica\Client;
use Elastica\Document;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class ArticleIndexer
{
private $client;
private $postRepository;
private $router;

public function __construct(Client $client, PostRepository $postRepository, UrlGeneratorInterface $router)
{
    $this->client = $client;
    $this->postRepository = $postRepository;
    $this->router = $router;
}

public function buildDocument(Post $post)
{
    return new Document(
        $post->getId(), // Manually defined ID
        [
            'title' => $post->getTitle(),
            'summary' => $post->getSummary(),
            'author' => $post->getAuthor()->getFullName(),
            'content' => $post->getContent(),

            // Not indexed but needed for display
            'url' => $this->router->generate('blog_post', ['slug' => $post->getSlug()], UrlGeneratorInterface::ABSOLUTE_PATH),
            'date' => $post->getPublishedAt()->format('M d, Y'),
        ],
        "article" // Types are deprecated, to be removed in Elastic 7
    );
}

public function indexAllDocuments($indexName)
{
    $allPosts = $this->postRepository->findAll();
    $index = $this->client->getIndex($indexName);

    $documents = [];
    foreach ($allPosts as $post) {
        $documents[] = $this->buildDocument($post);
    }

    $index->addDocuments($documents);
    $index->refresh();
}
}

运行研究时我无法获得结果,并且没有错误,所以我不知道我在配置中错过了什么。

0 个答案:

没有答案