I want to create a full text search with mongodb. How can I create the following query. With the query builder API?
db.Item.runCommand("text", {search: "Awesome"});
Is that possible? Or how can I execute a native query.
Thanks for help.
Make sure text search is enabled for your mongodb
http://docs.mongodb.org/manual/tutorial/enable-text-search/
The first step is to create an index in your document:
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* Class Item
* @MongoDB\Document(repositoryClass="Acme\StoreBundle\ItemRepository")
* @MongoDB\Indexes({
* @MongoDB\Index(keys={"title"="text"})
* })
*/
class Item
{
/**
* @MongoDB\Id
*/
protected $id;
//...
}
Then you can create the schema to ensure the index
php app/console doctrine:mongodb:schema:create
In your custom repository you can now query a command like this:
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html#custom-repository-classes
public function findFullText($searchTerm, $limit = 10)
{
$resultSet = new ArrayCollection();
//-- runCommand
$itemResultSet = $this->getDocumentManager()->getDocumentDatabase('AcmeStoreBundle:Item')->command([
'text' => 'Item',
'search' => $searchTerm,
'limit' => $limit
]);
foreach ($itemResultSet['results'] as $itemResult) {
$resultSet->add($this->uow->getOrCreateDocument('\Acme\StoreBundle\Document\Item', $itemResult['obj']));
}
return $resultSet;
}
This is probaby not the most sophisticated way. But it will provide you with the desired set of documents.