在 Symfony 3.4 mongodb 中进行全文搜索

Full text search in mongodb in Symfony 3.4

我正尝试在 mongodb:

中使用全文搜索

db.Product.createIndex({"name": "text"})
db.Product.find({$text: {$search: "xxxxx"}})

如何在 symfony 的控制器中使用它?

首先创建产品实体(根据您的需要调整)

<?php

/**
 * @Document
 * @Index(keys={"name"="text"})
 */
class Product
{
    /** @Id */
    public $id;

    /** @Field(type="string") */
    public $name;

    /** @Field(type="float") */
    public $price;
}

查看$name@Index注释

然后使用查询生成器 text() 方法

// Run a text search against the index
$qb = $dm->createQueryBuilder('Product')
    ->text('words you are looking for');

您可以找到更多信息 here

另一种方法是通过 doctrine query builder

使用 expr() 创建本机查询

谢谢大家的回答。总之,搜索引擎的控制器如下所示:

class SearchController extends Controller
{
  public function searchBarAction()
  {
    $form = $this->createFormBuilder(null)
        ->setMethod('GET')
        ->add('search', TextType::class)
        ->getForm();

    return $this->render('AppBundle:Components:_searchBar.html.twig', [
        'form' => $form->createView()
    ]);
 }

/**
 * @param Request $request
 */
public function handleSearchAction(Request $request)
{

    $searchData = $request->query->get('form')['search'];


    $dbName = 'ece';
    $connection = $this->container->get('doctrine_mongodb')->getConnection();
    $mongo = $connection->getMongo();
    $db = $mongo->selectDB($dbName);

    $resultSetProduct = $db->Product->find([
        '$text' => ['$search' => $searchData]
    ]);

    $resultSet = $db->MainData->find([
        '$text' => ['$search' => $searchData]
    ]);

    $itemProduct =  $resultSetProduct->count();
    $itemSet = $resultSet->count() + $itemProduct;


    return $this->render('search/index.html.twig', [
        'searchData' => $searchData,
        'resultSetProduct' => $resultSetProduct,
        'itemProduct' => $itemProduct,
        'itemSet' => $itemSet,
        'resultSet' => $resultSet

    ]);
 }
}