让Joomla! 支持中文全文检索,利用索引查询
相对与索引建立来说,查询稍为简单一些,如果你没有看到如何建立索引,请先看这篇文章:
让Joomla! 支持中文全文检索,建立索引
让我们在上次生成的组件中直接进行修改,来继续完成。首先来修改组件的视图文件view.html.php的display函数:
function display($tpl = null)
{
global $mainframe;
$lang = & JFactory :: getLanguage();
$lang->load('com_Lsearch');
$params = &$mainframe->getParams();
$items = array();
$searchword = JRequest::getVar('searchword');
if(! empty($searchword)) {
Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Phpbean_Lucene_Analyzer());
$index = new Zend_Search_Lucene('/home/apache/www/maycode/search');
$Query = Zend_Search_Lucene_Search_QueryParser::parse($searchword,'utf-8');
$hits = $index->find($Query);
$i = 0;
foreach ($hits as $hit) {
$items[$i]->title=$hit->title;
$items[$i]->content=JString::substr($hit->content,0,200);
$items[$i]->href=JRoute::_(ContentHelperRoute::getArticleRoute($hit->slug, $hit->catslug, $hit->sectionid));;
$i++;
}
}
$this->Assignref('Items',$items);
$this->Assign('Searchword',$searchword);
$this->Assignref('Params',$params);
parent::display($tpl);
}
程序的4-6行是基本都通用的,取得组件相关的参数,语言。
9行是取得查询的关键词,这个是通过form提交过来的。接下来我们会提到如何在模板文件中制作form。
10行是,判断如果输入了关键词,就进行查询。
程序11行,设置分词器
程序12行,打开已存在索引
程序13-14行,进行查询,返回结果集
程序16-21行,根据取得的结果集,组织传递给模板文件的数据。
视图文件就修改完成了,接下来我们看看模板文件:
<form id="searchForm" action="index.php?option=com_lsearch&view=lsearch" method="post" name="searchForm">
<table class="contentpaneopen ?>">
<tr>
<td nowrap="nowrap">
<label for="search_searchword">
<?php echo JText::_( 'Search Keyword' ); ?>:
</label>
</td>
<td nowrap="nowrap">
<input type="text" name="searchword" id="search_searchword" size="30" maxlength="20" value="<?php echo $this->escape($this->searchword); ?>" class="inputbox" />
</td>
<td width="100%" nowrap="nowrap">
<button name="Search" onClick="this.form.submit()" class="button"><?php echo JText::_( 'Search' );?></button>
</td>
</tr>
<input type="hidden" name="option" value="com_lsearch">
<input type="hidden" name="view" value="lsearch">
<input type="hidden" name="task" value="search">
</form>
<table class="contentpaneopen<?php echo $this->params->get( 'pageclass_sfx' ); ?>">
<tr>
<td>
<?php
foreach( $this->items as $result ) : ?>
<fieldset>
<div>
<span class="small<?php echo $this->params->get( 'pageclass_sfx' ); ?>">
<?php //echo $this->pagination->limitstart + $result->count.'. ';?>
</span>
<a href="/<?php echo JRoute::_($result->href); ?>" target="_blank">
<?php echo $this->escape($result->title);?>
</a>
</div>
<div>
<?php echo $result->content; ?>
</div>
<?php
if ( $this->params->get( 'show_date' )) : ?>
<div class="small<?php echo $this->params->get( 'pageclass_sfx' ); ?>">
<?php //echo $result->created; ?>
</div>
<?php endif; ?>
</fieldset>
<?php endforeach; ?>
</td>
</tr>
<tr>
<td colspan="3">
<div align="center">
<?php //echo $this->pagination->getPagesLinks( ); ?>
</div>
</td>
</tr>
</table>
模板文件,前一部分代码,生成了一个form,可以在其中输入关键词,进行查询。注意将其中的option,view,都改成你自己的组件相关的内容。
模板文件的后一部分代码,主要就是显示结果集。
注意:我们这里没有分页功能,同时在结果中也没有关键词反显功能。接下来,我会修改相关的代码,完成这两个功能的示例。