【问题标题】:Full text search in mongodb in Symfony 3.4Symfony 3.4 中 mongodb 中的全文搜索
【发布时间】:2019-01-02 14:01:05
【问题描述】:

我正在尝试在 mongodb 中使用全文搜索:

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

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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • $odm = $this->get('doctrine_mongodb.odm.document_manager'); $repo = $odm->getRepository(Product::class); $query = array('text' => 'name', 'search'=> 'XXXX'); $resultSet = $repo->find($query);
  • find 方法需要一个 id 才能工作。你试过findBy($query) 吗?

标签: mongodb symfony doctrine-odm


【解决方案1】:

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

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

另一种方法是使用来自学说查询构建器的 expr() 创建本机查询

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 2013-09-08
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多