如何在 Laravel 中进行 mongodb 文本搜索?请建议。
我可以在终端上做到这一点 -
db.coupons.find( { $text: { $search: "Search me here" } } )
Run Code Online (Sandbox Code Playgroud)
但不确定如何在 Laravel 中做到这一点。
要使用 laravel mongodb(使用 jenssegers/laravel-mongodb)进行搜索,您需要先创建一个索引。例如:db.articles.createIndex( { "subject" : "text" } ),subject进行搜索的文本属性在哪里。
然后你可以在 mongodb: 中尝试查询:db.articles.find( { $text: { $search: "coffee" } } )或者在 Laravel 中进行:
$word = "coffee";
$response = Article::whereRaw(array('$text'=>array('$search'=> $word)))->get();
Run Code Online (Sandbox Code Playgroud)
如果要按短语搜索,则需要使用引号。在 mongodb:db.articles.find( { $text: { $search: "\"coffee shop\"" } } )和 Laravel:
$word = "coffee shop";
$response = Article::whereRaw(array('$text'=>array('$search'=> "\"" . $word . "\"")))->get();
Run Code Online (Sandbox Code Playgroud)