0

我有类似于以下代码的内容:

[...]
while($result=mysql_fetch_assoc($query)){
    //Build a doc
    $doc = new Zend_Search_Lucene_Document();

    [...]

    $doc->addField(Zend_Search_Lucene_Field::text('category', sanitize($result["category"])));
    $all_values=explode(',',$result["value"]);
    $i=0;
    foreach ($all_values as $value) {
        $doc->addField(Zend_Search_Lucene_Field::text('value_'.($i++), urlencode($value)));
    }

    [...]

    //Add to doc
    $index->addDocument($doc);
}
[...]

现在我想只显示value_...搜索后得分较高的字段。

我怎么能做到?

4

1 回答 1

0

在对此进行了更多思考之后,我找到了解决问题的方法。

Zend Lucene 按分数对结果进行排序,因此,我需要为每个循环创建一个文档$valueforeach然后为我当前结果的 ID(称为res_id)创建一个索引,该索引位于 foreach 内部。这样,我可以res_id在搜索后以编程方式仅显示一个结果。

所以我的代码变成:

[...]
while($result=mysql_fetch_assoc($query)){
    $all_values=explode(',',$result["value"]);
    //Create a Doc foreach value of $all_values and gave them the same category of the result of the query
    foreach ($all_values as $value) {
        //Build a doc
        $doc = new Zend_Search_Lucene_Document();

        [...]

        //Added res_id just to help grouping the results
        $doc->addField(Zend_Search_Lucene_Field::unIndexed('res_id', sanitize($result["id"])));

        $doc->addField(Zend_Search_Lucene_Field::text('category', sanitize($result["category"])));
        //Renamed the field to value
        $doc->addField(Zend_Search_Lucene_Field::text('value', urlencode($value)));

        [...]

        //Add to doc
        $index->addDocument($doc);
    }
}
[...]

现在,当我进行搜索时,我只显示第一次出现的res_id(得分更高的那个)。

这是我在控制器上的代码,它向视图发送一个包含项目和找到的总项目的数组:

[...]
public function indexAction()
{
    $this->view->query=urldecode($this->_getParam("query"));
    if ($this->view->query){
        //open the index
        $index = new Zend_Search_Lucene('path/to/lucene/index');
        $hits = $index->find($this->view->query);
        $executed_ids=array();
        $total=0;
        $this->view->items=array();
        foreach ($hits as $hit) {
            //Pass item to view only if it is not listed yet on $executed_ids
            if (!$executed_ids[$hit->res_id]){
                $this->view->items[]=$hit;
                $executed_ids[$hit->res_id]=true;
                $total++;
            }
        }
        $this->view->total_hits=$total;
    }
}
[...]
于 2013-04-19T14:15:51.587 回答