简体   繁体   English

Laravel + Mongodb 全文搜索

[英]Laravel + Mongodb full text search

How do I make mongodb text search work in Laravel?如何在 Laravel 中进行 mongodb 文本搜索? Please suggest.请建议。

I can do that on terminal -我可以在终端上做到这一点 -

db.coupons.find( { $text: { $search: "Search me here" } } )

But not sure how to do it in laravel.但不确定如何在 Laravel 中做到这一点。

To search using laravel mongodb (with jenssegers/laravel-mongodb) you need to create an index first.要使用 laravel mongodb(使用 jenssegers/laravel-mongodb)进行搜索,您需要先创建一个索引。 Ex: db.articles.createIndex( { "subject" : "text" } ) , where subject is the text attribute to make the search.例如: db.articles.createIndex( { "subject" : "text" } ) ,其中subject是进行搜索的文本属性。

Then you can try a query in mongodb: db.articles.find( { $text: { $search: "coffee" } } ) or do it in Laravel:然后你可以在 mongodb 中尝试查询: db.articles.find( { $text: { $search: "coffee" } } )或在 Laravel 中执行:

$word = "coffee";
$response = Article::whereRaw(array('$text'=>array('$search'=> $word)))->get();

If you want to search by a phrase you need tu use the quotes.如果要按短语搜索,则需要使用引号。 In mongodb: db.articles.find( { $text: { $search: "\\"coffee shop\\"" } } ) and Laravel:在 mongodb 中: db.articles.find( { $text: { $search: "\\"coffee shop\\"" } } )和 Laravel:

$word = "coffee shop";
$response = Article::whereRaw(array('$text'=>array('$search'=> "\"" . $word . "\"")))->get();

Add jenssegers/laravel-mongodb package in your composer.json and install that through composer update .在 composer.json 中添加jenssegers/laravel-mongodb包并通过composer update安装它。 Visit added link, there you will get good source to deal with mongodb-laravel connection.访问添加的链接,在那里您将获得处理 mongodb-laravel 连接的良好来源。

Have you tried something like:您是否尝试过类似的事情:

$users = User::with(array('posts' => function($query)
{
    $query->where('title', 'like', '%first%');

}))->get();

See if that helps.看看是否有帮助。

Since you are using https://github.com/jenssegers/laravel-mongodb , according to your code you can do say由于您使用的是https://github.com/jenssegers/laravel-mongodb ,根据您的代码,您可以说

$coupons= Coupons::where('$text' =>['$search' =>'Search me here' ]); $coupons= Coupons::where('$text' =>['$search' =>'在这里搜索']);

}))->get(); }))->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM