1

我正在尝试在我的集合中搜索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);
    }
}
?>

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

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

任何人都可以用这个正则表达式语法的东西指出我正确的方向吗?

提前感谢您的帮助!

弥敦道

4

1 回答 1

3

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

你会像这样使用它(在 MongoDB shell 上):

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"' 
) );
于 2013-07-31T09:44:07.580 回答