在对此进行了更多思考之后,我找到了解决问题的方法。
Zend Lucene 按分数对结果进行排序,因此,我需要为每个循环创建一个文档$value
,foreach
然后为我当前结果的 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;
}
}
[...]