使用MongoDB Regex和PHP在字符串中搜索多个参数


Search Multiple Parameters in String with MongoDB Regex and PHP

我正在尝试在集合中搜索body属性包含所有搜索关键字的所有事件。

示例字符串-"The black cat is definitely purple."

关键字"black", "purple"将返回字符串。

关键字"black", "dog"返回该字符串。

我浏览了一些主题并在谷歌上搜索,但似乎找不到合适的语法。

目前,我正在获取一个由逗号分隔的关键字字符串,将其分解为一个数组,然后将其放入MongoRegex Object中。我知道我的语法是错误的,因为当我只发送一个关键字时,它是有效的,但当有多个关键字的时候,我不会得到任何我期望得到的结果。

当前方法:

<?php
function search_topics($array)
{
    include_once('config.php');
    $collection = get_connection($array['flag']);
    $x = 0;
    $string = null;
    $search_results = null;
    $keywords = explode(',', $array['search']); 
    $end_of_list = count($keywords);
    while ($x < $end_of_list)
    {
        $string = $string."/".$keywords[$x];
        $x++;
        if($x >= $end_of_list)
        {
            $string = $string."/i";
        }
    }
    if ($string != null)
    {   
        try
        {
            $regex_obj = new MongoRegex($string);
            $cursor = $collection->find(array('body' => $regex_obj));
        }
        catch (MongoCursorException $e)
        {
            return array('error' => true, 'msg' => $e->getCode());
        }
        foreach($cursor as $post)
        {
            $search_results[] = $post;
        }
        if ($search_results != null && count($search_results) > 1)
        {       
            usort($search_results, 'sort_trending');
        }
        return array('error' => false, 'results' => $search_results);
    }
    else
    {
        return array('error' => false, 'results' => null);
    }
}
?>

因此,如果我在$array['search']中发送字符串black,则我的对象由/black/i组成,并将返回该字符串。

如果我在$array['search']中发送字符串black,cat,则我的对象由/black/cat/i组成,并返回null

有人能用这个regex语法的东西给我指明正确的方向吗?

提前感谢您的帮助!

Nathan

我建议您改用MongoDB的文本搜索功能,而不是正则表达式,它是专门为以下情况而设计的:http://docs.mongodb.org/manual/core/text-search/

你可以这样使用(在MongoDB外壳上):

use admin
db.runCommand( { setParameter: 1, 'textSearchEnabled' : 1 } );
use test
db.so.ensureIndex( { string: 'text' } );
db.so.insert( { string: "The black cat is definitely purple." } );
db.so.runCommand( 'text', { search: '"cat" AND "dog"' } )
db.so.runCommand( 'text', { search: '"cat" AND "purple"' } )

命令不返回光标,而是返回一个文档,其中包含results字段中的所有查询结果。对于最后一个搜索命令,结果是:

{
    "queryDebugString" : "cat|purpl||||cat|purple||",
    "language" : "english",
    "results" : [
        {
            "score" : 2.25,
            "obj" : {
                "_id" : ObjectId("51f8db63c0913ecf728ff4d2"),
                "string" : "The black cat is definitely purple."
            }
        }
    ],
    "stats" : {
        "nscanned" : 2,
        "nscannedObjects" : 0,
        "n" : 1,
        "nfound" : 1,
        "timeMicros" : 135
    },
    "ok" : 1
}

在PHP中,为了让runCommand打开文本搜索,您可以使用:

$client->database->command( array( 
    'setParameter' => 1, 
    'textSearchEnabled' => 1 
) );

而文本搜索本身为:

$client->database->command( array(
    'text' => 'collectionName', 
    'search' => '"cat" AND "purple"' 
) );